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,AC代码如下:return [0, 1].
class Solution {
struct info{
int index;
int value;
};
public:
bool static cmp(info a,info b){
return a.value<b.value;
}
vector<int> twoSum(vector<int>& nums, int target) {
int length=nums.size();
info* infos=new info[length];
for(int i=0;i<length;i++){
infos[i].index=i;
infos[i].value=nums[i];
}
sort(infos,infos+length,cmp);
vector<int> v;
for(int i=0,j=length-1;i<j;){
if(infos[i].value+infos[j].value==target){
v.push_back(infos[i].index);
v.push_back(infos[j].index);
break;
}else if(infos[i].value+infos[j].value<target){
i++;
}else{
j--;
}
}
return v;
}
};