两数之和(1)
法一: class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: ret = [] for i in range(len(nums)): for j in range(1,len(nums)-i): if nums[i] + nums[-j] == target: ret.append(i) ret.append(len(nums)-j) return re 法二: class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashmap = {} for ind, num in enumerate(nums): hashmap[num] = ind for i, num in enumerate(nums): j = hashmap.get(target - num) if j is not None and i != j: return [i, j]
法三:
class Solution(object):
def twoSum(self, nums, target):
ret = []
for i in nums:
other = target-i
current_index = nums.index(i)
if other in nums[current_index+1:]:
other_index = nums[current_index+1:].index(other)
ret.append(current_index)
ret.append(current_index+other_index+1)
break
return ret