Givenan array of integers, return indices of the two numbers such that they add up to a specifictarget.
Youmay assume that each input would have exactly onesolution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
给你一个数组,问你是否有一个数等于数组中两个数的和,这题假如暴力解决的话,可能会超时,这里我没有暴力解决,我先把数组排序,然后设置start=0,end=nums.size()-1,当nums[start]+nums[end]<target的时候,start++,当nums[start]+nums[end]>target,end--,最后当nums[start]+nums[end]==target的时候start,end就是 最后的结果,
而这里当nums无序,的时候,当要求你输出nums中的索引的时候,有两种解决方案,其一是最后在遍历一次原来的nums,找到start和end在原数组中的索引,方法二是实用vector<pair<int,int>>num2第一个int表示nums2当前值在nums中对应的位置,第二个int表示当前位置的值,然后使用
boolcmp(pair<int,int> a,pair<int,int> b)
{
Returna.secont<b.second;
}
这样的最后一步的遍历nums也可以省去,直接返回nums2[start].first,和nums2[end].second就好了
class Solution {
public:
vector<int>twoSum(vector<int>& nums, int target) {
vector<int> nums2(nums.begin(),nums.end());
sort(nums.begin(), nums.end());
int start = 0; int end = nums.size() - 1;int tmp;
while (start != end)
{
tmp = nums[start] + nums[end];
if (tmp > target) end--;
else
if (tmp < target) start++;
else
{
break;
}
}
vector<int> result;
for (int i = 0; i < nums2.size(); i++)
if (nums2[i] == nums[start]) result.push_back(i);
else if (nums2[i] == nums[end])result.push_back(i);
return result;
}
};