zoukankan      html  css  js  c++  java
  • [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;
        }
    };
    

      

  • 相关阅读:
    Nginx 部署多个 web 项目(虚拟主机)
    Nginx 配置文件
    Linux 安装 nginx
    Linux 安装 tomcat
    Linux 安装 Mysql 5.7.23
    Linux 安装 jdk8
    Linux 安装 lrzsz,使用 rz、sz 上传下载文件
    springMVC 拦截器
    spring 事务
    基于Aspectj 注解实现 spring AOP
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3415906.html
Copyright © 2011-2022 走看看