zoukankan      html  css  js  c++  java
  • 15.3Sum (Two-Pointers)

    Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

    Note:

    • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
    • The solution set must not contain duplicate triplets.

    思路:首先大循环第一个数,从第一个数之后首尾指针向中间夹逼,时间复杂度O(n2)。需要注意跳过重复的数字。

    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            int size = nums.size();
            if(size < 3) return result;
            
            sort(nums.begin(), nums.end());
            find(nums, 1, size-1, -nums[0]);
            for(int i = 1; i < size-2; i++){
                if(nums[i]!=nums[i-1]) find(nums, i+1, size-1, -nums[i]);
            }
            return result;
        }
        void find(vector<int>& nums, int start, int end, int target){
            int sum;
            while(start<end){
                sum = nums[start]+nums[end];
                if(sum == target){
                    item.clear();
                    item.push_back(-target);
                    item.push_back(nums[start]);
                    item.push_back(nums[end]);
                    result.push_back(item);
                    do{ 
                        start++;
                    }while(start!= end && nums[start] == nums[start-1]);
                    do{ 
                        end--;
                    }while(end!=start && nums[end] == nums[end+1]);
                }
                else if(sum>target){
                    do{ 
                        end--;
                    }while(end!=start && nums[end] == nums[end+1]);
                }
                else{
                    do{ 
                        start++;
                    }while(start!= end && nums[start] == nums[start-1]);
                }
            }
        }
        
    private:
        vector<vector<int>> result;
        vector<int> item;
    };
  • 相关阅读:
    2.5(他们其实都是图)
    食物链POJ1182
    LG P6748 『MdOI R3』Fallen Lord
    LG P4199 万径人踪灭
    LG P1912 [NOI2009]诗人小G
    LG P4381 [IOI2008]Island
    2020/8/9 模拟赛 T3 表格
    UOJ422 【集训队作业2018】小Z的礼物
    CF913F Strongly Connected Tournament
    LG P5643 [PKUWC2018]随机游走
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4675179.html
Copyright © 2011-2022 走看看