三数之和 (写一篇正经的博客)

给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。

思路简单 枚举前两个 然后三分 。

主要是防重 操作 比如 一个数组 有 1 2 5 可以选 

 5 2 1 1 5 2 等都是重复的

所以每次枚举 前两个 然后 二分 最后一个到最后一个元素 ;

这样也会有重复 用 set 容器去重 ,加入set容器的数组要排序 不然去重不了。

然后 set输出时  得倒过来输出 ,因为set输出时 第一个元素绝对值大在后面、、

class Solution {
public:    
    /**
     * @param numbers : Give an array numbers of n integer
     * @return : Find all unique triplets in the array which gives the sum of zero.
     */
     
    
     int sanfen(int left, int right,vector< int> nums,int x)
    {
      if(left==right)
      return left;
       int mid1=(left+right)/2;
       if(nums[mid1]>=x)
        return sanfen(left,mid1,nums,x);
       else
        return sanfen(mid1+1,right,nums,x);

    }
    int panduan(int min,int max1,vector<int> nums)
    {
        int sum1=nums.size();//cout<<sum1<<endl;
        int home=0-nums[min]-nums[max1];

         int x1=-1;int x2=-1;int x3=-1;
         //if(min-1>=0)x1=sanfen(0,min-1,nums,home);
    // if(max1-1>=min+1)  x2=sanfen(min+1,max1-1,nums,home);//cout<<max1;
         if(max1+1<=sum1-1)  x3=sanfen(max1+1,sum1-1,nums,home);// cout<<x3<<endl;
        // if(nums[x1]==home)
        //return x1;
        // if(nums[x2]==home)
       //  return x2;
         if(nums[x3]==home)
         return x3;
         return -1;
    }
    vector<vector<int> > threeSum(vector<int> &nums)
    {
        set<vector<int>> s;
        bool xa=1;
        vector<vector<int> > po;
        vector<int> por;
        int x= nums.size();
        sort(nums.begin(),nums.end());
      for(int i=0;i<x;i++)
       for(int j=i+1;j<x;j++)
          { xa=1;
             int  x=panduan(i,j,nums);
             if(x!=-1)
              {
                  por.push_back(nums[i]);
                  por.push_back(nums[j]);
                  por.push_back(nums[x]);
                  //po.push_back(por);
                  sort(por.begin(),por.end());
                  s.insert(por);
                  por.clear();
                 
              }
            
          }
         set<vector<int>>::reverse_iterator rit;
       for(rit=s.rbegin();rit!=s.rend();rit++)
         po.push_back(*rit);
        
         reverse(po.begin(),po.end());
        return po;// write your code here
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值