Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
作为第一题本来以为能够在凌晨轻松A过,但还是too young了。
一开始的思路,最简单直接使用O(N^2)的暴力搜索,看有没有两个数加起来与target相等,代码如下:
<span style="font-size:14px;">int* twoSum(int* x, int n, int tag) {
int i,j,index[2];
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(x[i]+x[j]==tag)
{
index[0]=i+1;
index[1]=j+1;
}
}
return index;
}</span>
很明显,这样会TLE,所以没办法只能想着用hash来做,但由于在写题时没有用C++的习惯,导致直接使用一个数组来模拟hash,然后发现测试数据中存在需要索引为负数的数据。无奈,只能使用C++了。
通过C++中的map或hash_map存储这张表,完成常数级别的搜索,此题AC,代码如下:
<span style="font-size:14px;">class Solution {
public:
vector<int> twoSum(vector<int>& nums, int tag) {
map<int,int> f;
vector<int> index;
int n=0;
vector<int>::iterator iter;
for( iter = nums.begin(); iter != nums.end(); iter++ )
{
n++;
}
for(int i=0;i<n;i++)
{
map<int,int>::iterator l_it;
int k;
l_it=f.find(nums[i]);
if(l_it==f.end()) f.insert(pair<int,int>(nums[i],i));
l_it=f.find(tag-nums[i]);
if(l_it!=f.end())
{
k=l_it->second;
if(k<i)
{
index.push_back(k+1);
index.push_back(i+1);
}
}
}
return index;
}
};</span>
由于没有任何优化手段,运行时间为56ms,在所有A过的C++代码中处于比较差的。
其中有一点,由于长久未使用迭代器iterator,此处记下,通过pair添加进去的数据,调用迭代器指针时,使用l->first和l->second进行对数据的访问。