题目:
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
解法一:遍历,时间O(n2)
代码如下:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> result(2);
if(numbers.size()<=0)
return result;
for(int i=0;i<numbers.size();i++)
{
int num = target-numbers[i];
for(int j=i+1;j<numbers.size();j++)
{
if(numbers[j]==num)
{
result[0] = i+1;
result[1] = j+1;
return result;
}
}
}
return result;
}
};
解法二:先排序O(nlogn),在遍历O(n),时间复杂度为O(nlogn)
因为我们要知道元素的位置,所以我们排序时,需要记下该元素的初始索引index。
typedef struct node{
int val;
int ind;
node(){};
node(int v, int i) : val(v), ind(i){}
}Node;
bool comp(const Node & anode,const Node & bnode)
{
return (anode.val<bnode.val);
}
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> result(2);
if(numbers.size()<=0)
return result;
int len = numbers.size();
vector<Node> myvector(len);
for(int i=0;i<len;i++)
myvector[i] = Node(numbers[i],i);
sort(myvector.begin(),myvector.end(),comp);
int i=0, j=len-1;
while(i<=j)
{
int left = myvector[i].val;
int right = myvector[j].val;
if(left+right==target)
{
result[0] = min(myvector[i].ind,myvector[j].ind)+1;
result[1] = max(myvector[i].ind,myvector[j].ind)+1;
break;
}
else if(left+right<target)
i++;
else
j--;
}
return result;
}
};
这里空间复杂度是 O(n) ,时间复杂度是O(nlogn)。
解法三: 用Hash的思想,实现快速查表,可达到O(N)
具体关于 HashTable 的实现可以用 Map 数据结构 来实现,具体参考 博文 Hash Table的实现
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> result(2);
if(numbers.size()<=0)
return result;
int len = numbers.size();
map<long, int> hashTable;
for(int i=0;i<len;i++)
{
int ind = (target-numbers[i])*numbers[i];
if(hashTable[ind]>0)
{
if(numbers[i]+numbers[hashTable[ind]-1]==target)
{
result[0] = hashTable[ind];
result[1] = i+1;
break;
}
}
else
hashTable[ind] = i+1;
}
return result;
}
};