LeetCode 1.两数之和
语言:Python3
解法一
两次遍历列表每个元素,相加等于目标值返回下标值列表。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
状态 | 输入 | 输出 | 预期 |
---|---|---|---|
解答错误 | [3,2,4] 6 | [0,0] | [1,2] |
分析错误原因:
循环列表时,重复使用同一个列表元素。
如:i=0, j=0, nums[i] + nums[j] = target = 6, 返回了[0, 0],不符合预期
解决方法:不重复使用同一个列表元素。
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]
执行用时 | 内存消耗 |
---|---|
6856 ms | 14.2 MB |
解法二
遍历列表每个元素x,并查找是否存在一个值与 target−x 相等的目标元素。最后返回下标值列表。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
complement = target - nums[i]
try :
index = nums.index(complement, i + 1)
except ValueError:
pass
else:
return [i, index]
执行用时 | 内存消耗 |
---|---|
952 ms | 14.2 MB |
解法三
声明空字典,遍历列表,比较该元素的对应元素是否已经存在与字典中,如果存在,我们直接返回答案;不存在我们将列表值作为字典的键,下标值作为字典的值,存储在字典中。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = {}
for i in range(len(nums)):
complement = target - nums[i]
if complement in hashmap:
return [hashmap[complement], i]
else:
hashmap[nums[i]] = i # 将值作为键,下标值作为值,存储在字典中
执行用时 | 内存消耗 |
---|---|
36 ms | 14.5 MB |