您的位置:首页 > 其它

[LeetCode] Two Sum

2017-09-10 20:44 344 查看
[Problem]
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


[Solution]

// Definition for Element
struct Element{
int val;
int index;
Element(int v, int i) : val(v), index(i){}
};

// cmp
bool cmp(const Element &e1, const Element &e2){
if(e1.val < e2.val){
return true;
}
else if(e1.val == e2.val){
return e1.index < e2.index;
}
else{
return false;
}
}

// Definition for Solution
class Solution {
public:

// two sum
vector<int> twoSum(vector<int> &numbers, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// convert numbers into lements
vector<Element> array;
for(int i = 0; i < numbers.size(); ++i){
Element e(numbers[i], i+1);
array.push_back(e);
}

// sort element by val
sort(array.begin(), array.end(), cmp);

// search
vector<int> res;
int i = 0, j = numbers.size()-1;
while(i < j){
if(array[i].val + array[j].val == target){
res.push_back(min(array[i].index, array[j].index));
res.push_back(max(array[i].index, array[j].index));
break;
}
else if(array[i].val + array[j].val < target){
i++;
}
else{
j--;
}
}

return res;
}
};

 说明:版权所有,转载请注明出处。Coder007的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: