1 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
2 c++版本

1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 map<int,int> a;//建立hash表存放数组元素 5 vector<int> b(2,-1);//存放结果 6 for(int i=0;i<nums.size();i++) 7 a.insert(map<int,int>::value_type(nums[i],i)); 8 for(int i=0;i<nums.size();i++) 9 { 10 if(a.count(target-nums[i])>0&&(a[target-nums[i]]!=i)) 11 //判断是否找到目标元素且目标元素不能是本身 12 { 13 b[0]=i; 14 b[1]=a[target-nums[i]]; 15 break; 16 } 17 } 18 return b; 19 } 20 };
3 python版本

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 dict1={} 9 for i in range(0,len(nums)): 10 num=target-nums[i] 11 if num not in dict1: 12 dict1[nums[i]]=i 13 else: 14 return [dict1[num],i] 15 """ 16 hash_map=dict() 17 for i,x in enumerate(nums): 18 if target-x in hash_map: 19 return [i,hash_map[target-x]]; 20 hash_map[x]=i