在linux下码了,但是hashmap死活编译不过,,代码先转移:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ext/hash_map>
using namespace std;
using namespace __gnu_cxx;
class Solution{
public:
vector<int> twosum(vector<int>& numbers, int target){
vector<int> res;
if (numbers.empty())
return res;
hash_map<int, int> valMap;
for (size_t i = 0; i != numbers.size(); ++i){
valMap[numbers[i]] = i;
}
for (size_t i = 0; i < numbers.size(); ++i){
hash_map<int, int>::iterator iter = valMap.find(target-numbers[i]);
if (iter != valMap.end()){
res.push_back(i);
res.push_back(iter->second);
return res;
}
}
return res;
}
};
int main(){
vector<int> val;
for (int i = 0; i < 10; ++i){
val.push_back(i);
}
Solution so;
vector<int> res = so.twosum(val, 9);
if (res.empty()){
printf("can't find\n");
exit(1);
}
printf("find %d %d\n", res[0], res[1]);
exit(0);
}
可惜leetcode上这道题编译不过,还是用排序后搜索的办法吧:
class Solution{
private:
struct MyStruct
{
int val;
int index;
MyStruct(int val, int index):val(val), index(index){}
friend bool operator <(const MyStruct& t1, const MyStruct& t2){
return t1.val < t2.val;
}
};
public:
vector<int> twoSum(vector<int>& numbers, int target){
vector<int> res;
if (numbers.empty())
return res;
vector<MyStruct> tmpVec;
for (size_t i = 0; i != numbers.size(); ++i)
{
tmpVec.push_back(MyStruct(numbers[i], i));
}
std::sort(tmpVec.begin(), tmpVec.end());
int i = 0;
int j = tmpVec.size()-1;
while (i < j) {
int tmpSum = tmpVec[i].val + tmpVec[j].val;
if (tmpSum > target) {
--j;
}
else if (tmpSum < target){
++i;
}
else{
res.push_back(tmpVec[i].index+1);
res.push_back(tmpVec[j].index+1);
std::sort(res.begin(), res.end());
return res;
}
}
return res;
}
};
话说复杂度为O(N)+O(NlgN)+O(N)=O(NlgN)。
leetcode状态:accpeted!