zoukankan      html  css  js  c++  java
  • 【LeetCode 15】三数之和

    题目链接

    【题解】

    先把n个数字升序排个序。 然后枚举三元组最左边的那个数字是第i个数字。 之后用两个指针l,r移动来获取三元组的第2个和第3个数字。 (初始值,l=i+1,r = n-1); 如果a[i]+a[l]+a[r]>0 那么说明后面两个数字a[l]和a[r]太大了。 得让其中较大的那个数字a[r]变小一点。 也即r-- 否则l++即可。 这就给我们在一个一维数组中找两个数的和为x的二元组个数提供了思路。 即令l=1,r=n 若a[l]+a[r]>x那么,让r--. 否则让l++. (当然 前提是你是一个有序的数组。所以复杂度取决于排序的速度>_<(移动两个指针复杂度是O(N))的)

    【代码】

    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            vector<vector<int> > ans;
            vector<int> temp;
            temp.resize(3);
            sort(nums.begin(),nums.end());
            int len = nums.size();
            
            for (int i = 0;i < len;i++){
                if (i>0 && nums[i]==nums[i-1]) continue;//start 相同
                int l = i+1,r = len-1;
                while (l<r){
                    if (nums[i]+nums[l]+nums[r]==0){
                        temp[0] = nums[i],temp[1] = nums[l],temp[2] = nums[r];
                        ans.push_back(temp);
                        while (l+1<len && nums[l+1]==nums[l]) l++;
                        while (r-1>i && nums[r-1]==nums[r]) r--;
                        l++;r--;
                    }else if (nums[i]+nums[l]+nums[r]>0){
                        r--;
                    }else {
                        l++;
                    }
                    
                }
            }
            return ans;
        }
    };
    
  • 相关阅读:
    bzoj 3059: 归途与征程
    bzoj 4827: [Hnoi2017]礼物
    bzoj 4826: [Hnoi2017]影魔
    bzo j4825 [Hnoi2017]单旋
    hackerrank Week of Code 31
    bzoj 3615: MSS
    bzoj2505: tickets
    bzoj4813: [Cqoi2017]小Q的棋盘
    bzoj4821: [Sdoi2017]相关分析
    RedisTemplate访问Redis数据结构(一)——String
  • 原文地址:https://www.cnblogs.com/AWCXV/p/11808741.html
Copyright © 2011-2022 走看看