您的位置:首页 > 其它

LeetCode刷题笔记——1. 两数之和

2019-10-08 09:41 169 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_37046391/article/details/102365951

LeetCode刷题笔记——1. 两数之和

题目

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

利用两个循环解决

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1 , len(nums)):
if nums[i] + nums[j] == target:
return [i, j]

结果:

改进方法

利用python的字典来解决问题
首先,遍历列表,将列表中的第一个添加到字典当中。
在之后的列表中,每遍历一个节点,就在字典中寻找是否存在与其相加的和等于目标值的数,若存在则返回这两个数在列表中的位置,否则将该节点加入列表中并继续遍历下一个节点。

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = {}
for index, num in enumerate(nums):
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num], index]
hashmap[num] = index
return None


很明显,时间复杂度降低了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: