• 【leetcode】3Sum (medium)


    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.

    思路:

    把最小值从头到尾循环,中间值和最大值两边收缩。

    我写的时候是在最后去重复,总是超时。后来看了人家的答案,发现可以每次对最小、中间、最大值去重。就可以AC了

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <queue>
    #include <stack>
    using namespace std;
    
    class Solution {
    public:
        vector<vector<int> > threeSum(vector<int> &num) {
            vector<vector<int> > ans;
            if(num.size() < 3)
            {
                return ans;
            }
            int small = 0;
            int big = num.size() - 1;
            int mid = 0;
            int sum = 0;
            sort(num.begin(), num.end());
            for(small = 0; small < num.size() - 2; /*small++*/) //最小数字循环  中间与最大数字两边收缩
            {
                mid = small + 1;
                big = num.size() - 1;
                while(mid < big)
                {
                    sum = num[small] + num[mid] + num[big];
                    if(sum > 0)
                    {
                        big--;
                    }
                    else if(sum < 0)
                    {
                        mid++;
                    }
                    else
                    {
                        vector<int> v;
                        v.push_back(num[small]);
                        v.push_back(num[mid]);
                        v.push_back(num[big]);
                        ans.push_back(v);
                        do { mid++; }while (mid < big && num[mid - 1] == num[mid]); //注意!!
                        do { big--; }while (mid < big && num[big + 1] == num[big]);//注意!!
                    }
                }
                do{ small++; }while (small < num.size() - 1 && num[small - 1] == num[small]);//注意!!
            }
            return ans;
        }
    };
    
    int main()
    {
        Solution s;
        vector<int> num;
        num.push_back(-4);
        num.push_back(-1);
        num.push_back(-1);
        num.push_back(-1);
        num.push_back(-1);
        num.push_back(0);
        num.push_back(0);
        num.push_back(0);
        num.push_back(1);
        num.push_back(2);
    
        vector<vector<int>> ans = s.threeSum(num);
    
        return 0;
    
    
    }
  • 相关阅读:
    Python入门6 —— 流程控制
    Python入门5 —— 基本运算符
    Python入门4 —— 输入与输出
    实用小工具 下载链接
    [笔记] BGP in the Data Center (O'Reilly 2017)
    数据中心网络:Spine-Leaf 架构设计综述(2016)
    Using Open vSwitch* with DPDK for Inter-VM NFV Applications
    hung_task
    TCPDUMP and IPv6 and perf trace --no-syscalls
    Go非缓冲/缓冲/双向/单向通道
  • 原文地址:https://www.cnblogs.com/dplearning/p/4128127.html
Copyright © 2020-2023  润新知