【LeetCode】3Sum

参考:

http://blog.csdn.net/xshalk/article/details/8148422


题目描述

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)

题目分析

题目大意:给定一个数组,存在三个数a,b,c符合a+b+c=0。列出所有可能性。
输出要求,abc必须符合 a  ≤  b  ≤  c
思路:
这个可以转换为tow sum问题。逐个遍历数组,取出一个元素a,然后利用twosum问题找出两个相加等于b+c=-a。

对于2sum问题
需要先对数据进行排序。
把数组进行排序,然后首尾各定义一个指针head,tail,
如果target>(num[head]+num[tail]) tail--;
如果target<(num[head]+num[tail]) head++;

如果排序的复杂度为nlogn,那个3sum复杂度为n^2logn

代码示例

/*
编译环境CFree 5.0
博客地址:http://blog.csdn.net/Snowwolf_Yang
*/
#include 
     
     
      
      
#include 
      
      
       
       
using namespace std;
	
/*
vector
       
       
        
        
         
          > 后一个>前需要加一个空格 
*/

class Solution {
public:
    vector
         
          
          
            > threeSum(vector 
           
             &num) { vector 
             
             
               > ret; ret.clear(); sort(num.begin(),num.end()); for(int i=0; i!=num.size();i++){ if(i > 0 && num[i]==num[i-1]) //和前一个相同表示该子问题已经解决 continue; int j,k; j=i+1; k=num.size()-1; while(j 
              
                i+1&&num[j]==num[j-1]){ //和前一个相同表示该子问题已经解决 j++; continue; } if(k 
               
                 0){ k--; }else if(sum<0){ j++; }else{ vector 
                
                  tmp; tmp.push_back(num[i]); tmp.push_back(num[j]); tmp.push_back(num[k]); ret.push_back(tmp); j++; } } } return ret; } }; void test0() { int arr[] = {0,-1,2,3,-4,5,6,-7,8,9}; vector 
                 
                   numbers (arr, arr + sizeof(arr) / sizeof(int) ); Solution so; vector< vector 
                  
                    > out = so.threeSum(numbers); int i = 0,j = 0, flag = 1; for(i = 0;i 
                    
                   
                  
                 
                
               
              
             
            
           
         
        
        
       
       
      
      
     
     


推荐学习C++的资料

C++标准函数库
在线C++API查询







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值