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:
struct S{
int val,pos;
friend bool operator < (S &s1,S &s2){
return s1.val<s2.val;
}
};
vector<int> twoSum(vector<int>& nums, int target) {
int len=nums.size();
struct S s[len];
for(int i=0;i<len;++i){
s[i].val=nums[i];
s[i].pos=i;
}
sort(s,s+len);
vector<int> ans;
int h=0,r=len-1;
if(s[r].val+s[r-1].val<target||s[h].val+s[h+1].val>target) return ans;
while(h<r){
if(s[h].val+s[r].val==target){
ans.push_back(s[h].pos);
ans.push_back(s[r].pos);
break;
}else if(s[h].val+s[r].val<target){
++h;
}else{
--r;
}
}
return ans;
}
};