给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
暴力遍历
遍历x, 从x向后的位置查找y。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i,x in enumerate(nums):
y = target - x
if y in nums[i+1:]:
j = nums[i+1:].index(y)
return i,j+i+1
执行用时 : 872 ms
内存消耗 : 14.6 MB
字典
遍历x,借助字典来记录x之前的元素,这样就可以排除使用重复元素的可能性。此外,字典的使用极大地提高了查找速度。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for i,x in enumerate(nums):
if dict.get(target - x) is not None:
return dict[target - x],i
dict[x]=i
执行用时 : 60 ms
内存消耗 : 14.7 MB