您的位置:首页 > 其它

Leetcode-Two Sum

2014-10-07 15:45 302 查看
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

思路:固定一位,找剩下的元素,判断其和是否等于target

时间复杂度O(n^2)

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> res;
for(int i=0;i<numbers.size();i++)
for(int j=i+1;j<numbers.size();j++)
{
if(numbers[i]+numbers[j]==target)
{
res.push_back(i+1);
res.push_back(j+1);
return res;
}
}
return res;
}
};
提交的结果为:Time Limit Exceeded

下面做些优化:

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> res;
res.clear();
multimap<int,int> m;
multimap<int,int>::iterator mit;
multimap<int,int>::iterator mit2;
int i;
for(i=0;i<numbers.size();i++){
//m[numbers[i]]=i+1;
m.insert(pair<int,int>(numbers[i],i+1));

}
for(mit=m.begin();mit!=m.end();mit++)
{
if((mit2=m.find(target-mit->first))!=m.end()&&mit2!=mit)
{
if(mit->second>mit2->second)
{
res.push_back(mit2->second);
res.push_back(mit->second);
}
else
{
res.push_back(mit->second);
res.push_back(mit2->second);
}
return res;
}
}

return res;
}
};


find函数的底层实现是红黑树,时间复杂度为O(logn)

所以整个函数的时间复杂度为O(nlogn)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: