您的位置:首页 > 其它

[Leetcode]Two Sum

2013-10-17 10:16 603 查看
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

思路:使用一个struct保留排序前的下标号,然后设置两个下标index1,index2依次从前往后,从后往前

class Solution {
public:
struct node{
int val;
int index;
};
bool compare(const node& a, const node& b){
return a.val < b.val;
}
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
int index1 = 0;
int index2 = 0;
vector<node> resu_node;
node temp;
for(int i = 0;i < numbers.size();i++)
{
temp.index = i + 1;
temp.val = numbers[i];
resu_node.push_back(temp);
}

sort(resu_node.begin(),resu_node.end(),compare);

for(int i = 0,j = resu_node.size() - 1; i < j;)
{
if(resu_node[i].val + resu_node[j].val == target){
index1 = resu_node[i].index;
index2 = resu_node[j].index;
result.push_back(index1);
result.push_back(index2);
break;
}else if(resu_node[i].val + resu_node[j].val > target){
j--;
}else{
i++;
}
}

return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: