您的位置:首页 > 其它

leetcode-two sum

2014-10-31 10:28 357 查看
之前是通过hash来做,O(n)。这次为了熟悉通用性的解法,通过双指针来做。时间复杂度为O(nlogn)(即sort的复杂度)。

主要是关于sort的用法上不太熟,关于自定义sort规则。

C++ Reference中给的示例代码如下:


// sort algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector

bool myfunction (int i,int j) { return (i<j); }

struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;

int main () {
int myints[] = {32,71,12,45,26,80,53,33};
std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33

// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)

// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)

// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}


从中可以看到除了写compare函数外,还可以通过重载圆括号()来写函数对象。

一开始是写了个compare函数。

bool compare(const Node &lhs, const Node &rhs)
{
return lhs.val < rhs.val;
}
发现对于leetcode而言貌似只能提交class Solution内部的部分。而compare函数放在Solution内部就会出错,放在Solution外面就正常。为什么???
然后就通过重载圆括号写了函数对象,顺利通过。


class Solution {//two sum O(nlogn)
public:
struct Node{
int val;
int index;
Node(int v, int idx) :val(v), index(idx){}
};
struct myclass {
bool operator() (Node n1, Node n2) { return (n1.val<n2.val); }
} myobject;

vector<int> twoSum(vector<int> &numbers, int target) {
vector<Node> a;
for (int i = 0; i < numbers.size(); i++)
{
a.push_back(Node(numbers[i], i + 1));
}
sort(a.begin(), a.end(),myobject );
int i = 0, j = numbers.size() - 1;
vector<int> res;
while (i < j)
{
int sum = a[i].val + a[j].val;
if (sum == target)
{
int minIndex = min(a[i].index,a[j].index);
int maxIndex = max(a[i].index, a[j].index);
res.push_back(minIndex);
res.push_back(maxIndex);
break;
}
else if (sum < target)
{
i++;
}
else
{
j--;
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: