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].
法1 :暴力
1 class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 int looks ; 4 int[] res ={0,0}; 5 for(int i = 0;i<nums.length;i++){ 6 looks = target - nums[i]; 7 for(int j = i+1;j<nums.length;j++){ 8 if((looks == nums[j])) { 9 res[0] = i; 10 res[1] = j; 11 } 12 } 13 } 14 return res; 15 } 16 }
法2:利用dict 映射,
遍历一遍list,将target减去当前元素的差作为key,当前元素的下标为val
如果当前元素是字典的key ,则返回当前元素的下标,与字典中当前元素对应的val
1 class Solution: 2 def twoSum(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 n_dict = {} 9 for i in range(len(nums)): 10 if nums[i] in n_dict.keys(): 11 return [n_dict[nums[i]],i] 12 else: 13 n_dict[target-nums[i]] = i; 14
20180325
用 key in dict: 判断效率更高!!!
时间复杂度 o(n)
空间复杂度 o(n)
1 class Solution: 2 def twoSum(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 n_dict = {} 9 for i,item in enumerate(nums): 10 val = target - item 11 if item in n_dict: 12 return [n_dict[item],i] 13 else: 14 n_dict[val] = i