zoukankan      html  css  js  c++  java
  • 【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;
    
    
    }
  • 相关阅读:
    树的直径、重心、中心
    DP优化--四边形不等式
    P5569 【SDOI2008】 石子合并(黑科技)
    P3147 262144游戏
    P3205 【HNOI2010】合唱队
    Windows Server 2012 虚拟化实战:网络(一)
    Windows Server 2012 虚拟化实战:存储(二)
    Android使用最小宽度限定符时最小宽度的计算
    Eclipse调试Android App若选择“Use same device for future launches”就再也无法选择其他设备的问题
    Python的模块引用和查找路径
  • 原文地址:https://www.cnblogs.com/dplearning/p/4128127.html
Copyright © 2011-2022 走看看