设为首页 加入收藏

TOP

Leetcode--3Sum
2015-07-24 05:39:19 来源: 作者: 【 】 浏览:7
Tags:Leetcode--3Sum

Problem Description:

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, 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,具体实现用到了upper_bound函数找到比当前数大的第一个数,去掉重复循环的情况,然后用find函数查找c是否存在,存在则将三个数记录下来。具体代码如下:

    class Solution {
    public:
        vector
        
          > threeSum(vector
         
           &num) { vector
          
            > results; if(num.size()<3) return results; vector
           
             subset; sort(num.begin(),num.end()); vector
            
             ::iterator p=num.begin(),q,flag; while(p<(num.end()-2)) { q=p+1; while(q
             
              

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu 4717 The Moving Points(三.. 下一篇[POJ 3734] Blocks (矩阵快速幂、..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: