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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
题解
这是K sum题型的基础模型,题意就是在一个数组中找到和为target的所有的 【K个数组合】 。
方法a
简单做法就是遍历k遍,时间复杂度为O(n^k)。代码略。
- 方法b
如果要求返回的是数本身,则可以先排序,然后头尾夹逼。这一题不符,代码就不写了。 - 方法c
借助哈希表来标记,然后找差。
//cpp
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res(2,0);
map<int,int> flag;
for(int i=0;i!=nums.size();i++)
{
int sub=target-nums[i];
if(flag.find(sub)!=flag.end())
{
res[0]=flag[sub];
res[1]=i;
return res;
}
flag[nums[i]]=i;
}
return res;
}
};