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:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> xxx(numbers);//因为要返回索引,就用一个备份来排序
int len = numbers.size();
sort(xxx.begin(), xxx.end());
int i = 0, j = len - 1;
while(i < j)
{
if(xxx[i] + xxx[j] > target)//此时j减小,即xxx[j]减小
{
j--;
}
else if(xxx[i] + xxx[j] < target)//此时i增大,即xxx[i]增大
{
i++;
}
else//相等了!!!
{
break;
}
}
vector<int> x;
if(i < j)
{
for(int k = 0; k < len; k++)
{
if(i >= 0 && numbers[k] == xxx[i])
{
x.push_back(k + 1);
i = -1;
}
else if(j >= 0 && numbers[k] == xxx[j])//如果没有这个else,当xxx[i] == xxx[j]时就纠结了
{
x.push_back(k + 1);
j = -1;
}
}
}
return x;
}
};
本文介绍了一种解决两数之和问题的算法实现。给定整数数组及目标值,寻找两个数使它们的和等于目标值,并返回这两个数的索引。文章通过排序与双指针技巧实现了高效的解决方案。
754

被折叠的 条评论
为什么被折叠?



