给定一个整数数组,返回这两个数字的索引,使它们合计成一个特定的目标。
您可能会认为每个输入都只有一个解决方案,并且您可能不会使用相同的元素两次。
例:
鉴于NUMS = [2,7,11,15],目标= 9, 因为NUMS [ 0 ] + NUMS [ 1 ] = 2 + 7 = 9, 返回[ 0,1 ]。
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, 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].
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>cdata(nums);//用于存储排序数据
vector<int>index;
partial_sort_copy(nums.begin(),nums.end(),cdata.begin(),cdata.end());
int i =0,j=cdata.size()-1;
int result =cdata.at(i)+cdata.at(j);
while(result!=target)
{
if(result>target){
--j;
}
else{++i;}
result=cdata.at(i)+cdata.at(j);
}
int pos = find(nums.begin(), nums.end(), cdata.at(i)) - nums.begin();
index.push_back(pos + 1);//将元素X加入到c容器的最后一位。
nums.at(pos) = cdata.at(j) + 1;//防止该位置被二次检索
index.push_back(find(nums.begin(), nums.end(), cdata.at(j)) - nums.begin() + 1);
sort(index.begin(), index.end());
return index;
}
};