leetcode--001. Two Sum

来源:互联网 发布:知是故人来 编辑:程序博客网 时间:2024/06/05 15:11

Two sum

题意

给一个整数数组和数 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;    }};
0 0
原创粉丝点击