一道简单题,难了我半天,手有些生疏了。
总结下大佬的方法把:
Python解法:
方法一: 找到 anotherNum= target-num[i], 检查是否在list中,
若在: (1)判断该数出现1次,两个数相等,说明找的是自身
(2)判断该数出现多次,从该数后面开始找,需要判断找到的下标是否合法,检查。
def twoSum(nums, target):
lens = len(nums)
j=-1
for i in range(lens):
if (target - nums[i]) in nums:
if (nums.count(target - nums[i]) == 1)&(target - nums[i] == nums[i]):#如果num2=num1,且nums中只出现了一次,说明找到是num1本身。
continue
else:
j = nums.index(target - nums[i],i+1) #index(x,i+1)是从num1后的序列后找num2
break
if j>0:
return [i,j]
else:
return []
方法二:使用hashmap和python内置函数enumerate(nums),生成对应键值对。两种方式,先放进hashmap用第一个值找,也可每次找当前元素之前的是否有满足条件的值
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: 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