leetcode 1. Two Sum
2019-06-21 本文已影响0人
PJCK
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
python代码
这个题就是利用字典,保存nums里面的数和其位置,然后用暴力枚举就完事了。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
length = len(nums)
for i in range(length):
dic[nums[i]] = i
for i in range(length):
res = target - nums[i]
if res in dic.keys() and dic.get(res) != i: #这个代码中dic.get(res)也可以用dic[res]代替
return [i, dic.get(res)]