您的位置:首页 > 其它

[leetcode笔记] Two-sum

2014-07-23 17:09 302 查看
注册了leetcode账号,一共有150道题,准备有时间就刷一刷,许久没有编程了,C++早已生疏。

目前leetcode也支持Python了,俺们还是先练练C++。先找个简单的开始,随便挑了一个AC率稍微高点的题"Two Sum"。

Two Sum

https://oj.leetcode.com/problems/two-sum/

Total Accepted: 25599 Total Submissions: 140441

问题描述:

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

解题报告:

(1)第一次Submit

先用最土的办法试试:

class Solution {
public:
vector<int> twoSum_01_timeout(vector<int> &numbers, int target) {

int a = 0, b = 0;
bool breakFlag = false;
for(a = 0; a < (int)numbers.size()-1; a++)
{
for(b=a+1; b< (int)numbers.size(); b++)
{
if(numbers[a] + numbers[b] == target)
{
breakFlag = true;
break;
}
}
if(breakFlag==true){ break; }
}

vector<int> rv(2);
rv[0] = a+1;
rv[1] = b+1;
return rv;
}
}


不出意外,Timeout!哪能这么简单!

(2)第二次Submit

改进一下,先搞个排序试试,复习了一下STL sort方法用法。

bool lesspair(const pair<int,int>& p1, const pair<int,int>& p2 )
{
return p1.first < p2.first;
}

void print_pair_vector(vector<pair<int,int>>& ns)
{
int i = 0;
for(i=0; i<static_cast<int>(ns.size()); i++)
{
cout<< "(" << ns[i].first << ", " << ns[i].second << ")  ";
}
}

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {

vector<pair<int,int>> ns;
int i = 0;
for(i = 0; i<static_cast<int>(numbers.size()); i++)
{
pair<int,int> p(numbers[i], i+1);
ns.push_back(p);
}

//print_pair_vector(ns);
sort(ns.begin(), ns.end(), lesspair);
//print_pair_vector(ns);

int a = 0, b = 0;
bool breakFlag = false;
for(a = 0; a < (int)ns.size()-1; a++)
{
for(b=a+1; b< (int)ns.size(); b++)
{
if(ns[a].first + ns[b].first == target)
{
breakFlag = true;
break;
}
}
if(breakFlag==true){ break; }
}

vector<int> rv(2);
if ( ns[a].second < ns[b].second )
{
rv[0] = ns[a].second;
rv[1] = ns[b].second;
}
else
{
rv[0] = ns[b].second;
rv[1] = ns[a].second;
}
return rv;
}
};


刚开始没搞对返回值顺序,稍作修改再次提交。Accepted!不会吧,这就过了?

感觉俺的方法还是有点土啊![汗]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: