• [LeetCode]3Sum


    Given an array S of n integers, are there elements a, b, c 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, abc)
    • The solution set must not contain duplicate triplets.
        For example, given array S = {-1 0 1 2 -1 -4},
    
        A solution set is:
        (-1, 0, 1)
        (-1, -1, 2)
    

     思考:仿照在2Sum,增加一个循环遍历数组,复杂度O(n2)。一直纠结于是否存在O(nlogn)的解法?最初思路是在2Sum的基础上,二分搜索(0-num[i]-num[j])。未能解决搜索成功后i,j的变化。

    class Solution {
    public:
        vector<vector<int> > threeSum(vector<int> &num) {
            vector<vector<int> > res;
            vector<int> ans;
            sort(num.begin(),num.end());
            int len=num.size();
            for(int i=0;i<len-2;i++)
            {
                if(i&&num[i]==num[i-1]) continue;
                int left=i+1;
                int right=len-1;
                while(left<right)
                {
                    if(left>i+1&&num[left]==num[left-1]) 
                    {
                        left++;
                        continue;
                    }
                    if(right<len-1&&num[right]==num[right+1]) 
                    {
                        right--;
                        continue;
                    }
                    if(num[i]+num[left]+num[right]==0)
                    {
                        ans.clear();
                        ans.push_back(num[i]);
                        ans.push_back(num[left]);
                        ans.push_back(num[right]);
                        res.push_back(ans);
                        left++;
                        right--;
                    }
                    else if(num[i]+num[left]+num[right]>0) right--;
                    else left++;
                }
            }
            return res;
        }
    };
    

      

  • 相关阅读:
    VRChat之blender教程
    29(30).socket网络基础
    26(27).反射及面向对象进阶
    25.python之面向对象
    24.configparser&hashlib
    23.logging
    22.re(正则表达式)
    22.XML
    java日志系统 @Slf4j注解的正确使用
    java四种元注解:@Retention @Target @Document @Inherited)认知
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3415906.html
Copyright © 2020-2023  润新知