Link: https://oj.leetcode.com/problems/two-sum/
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
要求为给出的数组中,找出两个数字相加为指定的数,已知数组中只有唯一一组相加为给定值的的正确组合,所求是俩个值所在位置(非0开始)
思路:由于答案唯一,每两个数值两两相加可以得到。
1 将数组排序,指向头尾两个数字
2 两个数字相加后,如果大于所给值,需要一个减小的过程,所指尾部位置-1,缩减相加的量;如果小于所给值,头部位置+1,增加所加的量。
3 重复第2步,总能获得相加等于给定值的两个数字,注意求为位置,不是数值。
由于过程需要排序,所以需要复制数组以保存原数组的位置。
由值求原数组位置时,注意如果求出的两个值为相同时,将获得两个相同位置:
[3,4,1,4,9,2,10],求8,排序为[1,2,3,4,4,9,10],从4,4获得4个位置,将取不同的两个位置为答案
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> nums = numbers; // 拷贝数组以保存原位置
sort(nums.begin(),nums.end());
int beg = 0, end = nums.size()-1;
vector<int> re;
for(;beg<end;)
{ if(nums[beg]+nums[end]> target) {
--end;
}
else if(nums[beg]+nums[end]< target){
++beg;
}
else
{ for(unsigned long i=0; i<numbers.size();i++){ // 将位置入栈,如果[beg]==[end]时,获得4个位置
if(numbers[i]==nums[beg])
re.push_back(i+1);
if(numbers[i]==nums[end])
re.push_back(i+1);
}
if(re.size()>2) {
re[1]=re[2]; // 4个位置时,调换相同值
}
return re;
}
}
return re;
}
};