zoukankan      html  css  js  c++  java
  • LeetCode_3Sum

     1 class Solution {
     2 public:
     3     vector<vector<int> > threeSum(vector<int> &num) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         vector<vector<int> > output; 
     7         if(num.size()<3) return output; 
     8          
     9         sort(num.begin(), num.end());
    10         
    11         for(int i =0; i< num.size() -2 ;){
    12             int startS = i + 1 ;
    13             int endS = num.size() - 1 ;
    14             while(startS < endS){
    15              
    16              int sum = num[i] + num[startS] + num[endS];
    17              if(sum == 0) {
    18                     vector<int> triplet;  
    19                     triplet.push_back(num[i]);  
    20                     triplet.push_back(num[startS]);  
    21                     triplet.push_back(num[endS]);  
    22                     output.push_back(triplet);  
    23                     startS++ ;
    24                     while(num[startS] == num[startS-1] && startS < endS) startS++;
    25              }
    26              if(sum < 0)
    27                    startS ++;
    28              else
    29                     endS --;    
    30             }   
    31             i++;
    32             while(num[i] == num[i-1] && i< num.size() -2) i ++;     
    33         }        
    34         return output;
    35     }
    36 };

    和3Sum closest 类似,注意删除重复的三元组就行

    --------------------------------------------------------------------天道酬勤!
  • 相关阅读:
    hdu 5366 简单递推
    hdu 5365 判断正方形
    hdu 3635 并查集
    hdu 4497 数论
    hdu5419 Victor and Toys
    hdu5426 Rikka with Game
    poj2074 Line of Sight
    hdu5425 Rikka with Tree II
    hdu5424 Rikka with Graph II
    poj1009 Edge Detection
  • 原文地址:https://www.cnblogs.com/graph/p/3006543.html
Copyright © 2011-2022 走看看