# Two Sum

368人阅读 评论(0)

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

class Solution {
public:
template <typename T>
vector<size_t> sort_indexes(vector<T> &v) {

// initialize original index locations
vector<size_t> idx(v.size());
for (size_t i = 0; i != idx.size(); ++i) idx[i] = i;

// sort indexes based on comparing values in v
sort(idx.begin(), idx.end(),
[&v](size_t i1, size_t i2) {return v[i1] < v[i2];});
sort(v.begin(), v.end());
return idx;
}
int select(vector<int>& nums, int start, int end, int value)
{
if(start > end)
return -1;
if(nums[(start + end)/2] == value)
return (start + end)/2;
else if(nums[(start + end)/2] < value)
{
start = (start + end)/2 + 1;
select(nums, start, end, value);
}
else{
end = (start + end)/2 -1;
select(nums, start, end, value);
}
}
vector<int> twoSum(vector<int>& nums, int target) {
//sorted nums ascendingly.
vector<size_t> sorted_indexes = sort_indexes(nums);

int result;
vector<int> two_sum;
for(int i = 0; i < nums.size(); i++)
{
//look for number = target-nums[i]
int index = select(nums, i+1, nums.size() - 1, target-nums[i]);
if(index != -1)
{
int a1 = 0;
int a2 = 0;

if(sorted_indexes[i] < sorted_indexes[index]){
a1 = sorted_indexes[i]+1;
a2 = sorted_indexes[index] + 1;
}
else{
a1 = sorted_indexes[index] + 1;
a2 = sorted_indexes[i]+1;
}
two_sum.push_back(a1);
two_sum.push_back(a2);
return two_sum;
}
}
return two_sum;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：198463次
• 积分：2342
• 等级：
• 排名：第16543名
• 原创：79篇
• 转载：6篇
• 译文：0篇
• 评论：140条
我的博客
weibo：http://weibo.com/pkubrooks/home github： https://github.com/guoyilin
评论排行
最新评论