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(N^2)
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> container;
for (int i=0; i<numbers.size();i++)
for (int j=0; j<numbers.size(); j++)
{
if (j==i)
continue;
if (numbers[i]+numbers[j]==target)
{
container.push_back(++i);
container.push_back(++j);
return container;
}
}
}
};
第二次, O(NlogN)
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> container;
map<int,int> myMap;
// copy data into map O(N)
for (int i=0; i<numbers.size();i++)
myMap[numbers[i]]=i; //O(lgN)
// O(NlogN)
// loop the array O(N)
for (int j=0; j<numbers.size();j++)
{
int obj=target-numbers[j];
//Log(N)
map<int,int>::iterator it=myMap.find(obj);
if (it!=myMap.end() && it->second!=j)
{
container.push_back(j+1);
container.push_back(it->second+1);
return container;
}
}
//Nlog(N)
}
};
基本有这么基础知识:
1. map 是 红黑树, 插入是 long(N), 搜索是logN.
2. map的一些基本method, insert, [], find, pari<>. 理解map[]的覆盖。 这个题目因为说了肯定有一对解,所以不用担心覆盖问题
3. 基本上就是map用数值做key然后搜索,比O(N^2)快点
</pre><p>今天做3sum的时候想起来2sum有个排序的方法,稍微啰嗦,空间不算太优化,但是3sum可能会用到。。。这里写一下。。。</p><p></p><p><pre name="code" class="cpp">class Solution {
public:
struct Node {
int val;
int index;
Node(int v, int i)
:val(v),index(i){};
};
static bool compare(const Node& a,const Node& b)
{
return a.val<b.val;
}
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> index;
vector<Node> temp;
for (int i=0;i<numbers.size();i++)
temp.push_back(Node(numbers[i],i));
sort(temp.begin(),temp.end(),compare);
int beg=0;
int end=temp.size()-1;
while(beg<end){
int sum=temp[beg].val+temp[end].val;
if (sum==target)
{
int ind1=temp[beg].index+1;
int ind2=temp[end].index+1;
if (ind1>ind2)
swap(ind1,ind2);
index.push_back(ind1);
index.push_back(ind2);
return index;
}
if (sum<target)
beg++;
if (sum>target)
end--;
}
}
};