1.Problem Description
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].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question.
在给定数组中找到两个数,其和等于给定的value。
2. My solution(O(n^2)实现)
太简单了。
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
int i=0,j=0;
int len=nums.size();
vector<int>result;
for(i; i<len; i++)
{
for(j=0; j<len; j++)
{
if(i==j)
continue;
if(nums[i]+nums[j]==target)
{
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return result;
}
};
3. My solution2(O(n)实现)
O[n^2]竟然过了,看discuss才发现O[n]的做法,用了hashtable。
把每个数在数组中出现的位置用map存起来,这里注意为了判断是否存在这个数,我们把所以index加一,也就是对于[3,2,4]他们在hashtable中的index不是0,1,2而是1,2,3.这样我们就可以用他在hashtable中的index是否为0判断这个数是否存在了。
class Solution
{
private:
map<int,int>ht;
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int>res;
int len=nums.size();
for(int i=0; i<len; i++)
{
int tmp=nums[i];
ht[tmp]=i+1;
}
for(int i=0; i<len; i++)
{
int tmp=nums[i];
if(ht[target-tmp]>0&&ht[target-tmp]-1!=i)
{
res.push_back(i);
res.push_back(ht[target-tmp]-1);
return res;
}
}
return res;
}
};