题意
给一个整数数组和数 target,返回数组中某两个数相加之和为 target 的下标。
题解
思路见代码。
时间复杂度:
O(nlogn)
class Solution {
public:
struct node{
int val, pos;
node(int v, int p):val(v), pos(p){}
};
vector<int> twoSum(vector<int>& nums, int target) {
vector<node> res;
vector<int> ans;
int n = nums.size();
for(int i = 0; i < n; ++i){
res.push_back(node(nums[i], i));
}
sort(res.begin(), res.end(), [](const node& n1, const node& n2){ return n1.val < n2.val; });
int l = 0, r = n - 1;
while(l < r){
if(res[l].val + res[r].val == target) break;
else if(res[l].val + res[r].val > target) r--;
else l++;
}
ans.push_back(res[l].pos);
ans.push_back(res[r].pos);
return ans;
}
};