LeetCode 1.两数之和
题目描述
给定一个整型数组,要求返回两个数的下标,使得两数之和等于给定的目标值,要求同一个下标不能使用两次。
数据保证有且仅有一组解。
样例
给定数组 nums = [2, 7, 11, 15],以及目标值 target = 9,
由于 nums[0] + nums[1] = 2 + 7 = 9,
所以 return [0, 1].
算法:unordered_map(哈希表)
Text
1 Class solution{ 2 public: 3 vector<int> twoSum(vector<int>& nums, int target){ 4 unordered_map<int,int>hash; 5 vector<int>res; 6 for(int i=0;i<nums.size();i++){ 7 int another=target-nums[i]; 8 if(hash.count(another)){ 9 res.push_back(i,hash[another]); 10 break; 11 } 12 hash[nums[i]]=i; 13 } 14 return res; 15 } 16 };