问题描述:https://leetcode.com/problems/two-sum/
<pre name="code" class="cpp"><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Given an array of integers, find two numbers such that they add up to a specific target number.</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">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.</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">You may assume that each input would have exactly one solution.</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-size: 14px; line-height: 30px; font-family: monospace;"><span style="box-sizing: border-box; font-weight: 700;">Input:</span> numbers={2, 7, 11, 15}, target=9<br style="box-sizing: border-box;" /><span style="box-sizing: border-box; font-weight: 700;">Output:</span> index1=1, index2=2</p>
问题关键在于,对vector进行排序,排序之后,index1和index2指针一个从前一个从后开始向中间扫描。刚开始的时候,想着直接使用vector自带的排序,但是怕LeetCode没有包含algorithm头文件,所以使用选择排序,但是超时了。最后,到网上一看,发现原来LeetCode包含了algorithm头文件的。
代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> tempv(nums);
sort(tempv.begin(), tempv.end());
int index1 = 0, index2 = tempv.size()-1;
while (tempv[index1]+tempv[index2]!=target)
{
if (tempv[index1] + tempv[index2] < target)
index1++;
else
index2--;
}
int start = tempv[index1], end = tempv[index2];
int i = 0;
while (nums[i] != start)
{
i++;
}
vector<int> rs;
start=i+1;
i = nums.size() - 1;
while (nums[i] != end)
i--;
end=i+1;
rs.push_back(start<end?start:end);
rs.push_back(start<end?end:start);
return rs;
}
};
本文针对LeetCode经典题目“两数之和”,提供了一种有效的解决方案。通过对数组排序并采用双指针技术,实现寻找两个数相加等于特定目标值的索引。文章详细介绍了算法思路及代码实现。
176

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



