• [Leetcode] 3sum 三数和


    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.
        For example, given array S = {-1 0 1 2 -1 -4},
    
        A solution set is:
        (-1, 0, 1)
        (-1, -1, 2)

    题意:给定值0,使三数之和等于0,返回所有情况。

    思路:这题的思路和3sum closest类似。关键在于去重。代码如下:

     1 class Solution {
     2 public:
     3     vector<vector<int> > threeSum(vector<int> &num) 
     4     {
     5         vector<vector<int>> res;
     6         sort(num.begin(),num.end());
     7         if(num.size()<3)    return res;
     8 
     9         for(int i=0;i<num.size()-2;++i)
    10         {
    11             if(num[i]>0)   break;  //最小值大于0,返回空
    12             if(i>0&&num[i]==num[i-1]) continue;   //去重
    13             int l=i+1,r=num.size()-1;
    14             while(l<r)
    15             {
    16                 int sum=num[i]+num[l]+num[r];
    17                 if(sum==0)
    18                 {
    19                     res.push_back({num[i], num[l], num[r]});
    20                     //去重
    21                     while(++l<r&&num[l-1]==num[l])
    22                         ;
    23                     while(--r>l&&num[r]==num[r+1])
    24                        ;
    25                 }
    26                 else if(sum<0)
    27                     ++l;
    28                 else
    29                     r--;
    30 
    31             }
    32         }
    33         return res;    
    34     }
    35 };
  • 相关阅读:
    Web后台框架 目录
    C++ 目录
    【花书笔记】线性代数
    【Python数据挖掘概念、方法与实践】
    【统计学习基础】2. Overview of Supervised Learning
    字节与16进制
    【西瓜书】线性模型
    MySQL入门经典
    【机器学习基石】感知机模型
    python:web应用程序
  • 原文地址:https://www.cnblogs.com/love-yh/p/7108695.html
Copyright © 2020-2023  润新知