1.Two Sum
这道题为简单题
题目:
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].
思路:
这道题可以利用字典,遍历列表,如果target - nums[i] 在a中,那么就返回该元素和a[target - nums[i]]的索引,否则就添加该元素到字典中,键值为索引值
代码:
1 class Solution(object): 2 def twoSum(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 a = {} 9 for i in range(len(nums)): 10 if target - nums[i] in a: return [i, a[target - nums[i]]] 11 else: a[nums[i]] = i 12 return None