码迷,mamicode.com
首页 > 其他好文 > 详细

3Sum

时间:2015-05-11 14:18:39      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:

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)


分析:先对数组进行排序,先固定第一个数,然后两边夹逼。特别要注意的地方是 如何排除相同的结果

进行排序后,连续的几个数字可能相同。因此,要略过相同的数字进行检查。运行时间65ms
 1 class Solution {
 2 public:
 3     vector<vector<int> > threeSum(vector<int>& nums) {
 4         vector<vector<int> > result;
 5         if(nums.size() < 3) return result;
 6         sort(nums.begin(), nums.end());
 7         
 8         for(int a = 0; a < nums.size() - 2; a++){
 9             if(a != 0 && nums[a] == nums[a-1]) continue;
10             int b = a + 1, c = nums.size() - 1;
11             while(b < c){
12                 if(nums[a] + nums[b] + nums[c] > 0) c--;
13                 else if(nums[a] + nums[b] + nums[c] < 0) b++;
14                 else{
15                     if(b != a + 1 && nums[b] == nums[b-1]) b++;
16                     else if(c != nums.size() - 1 && nums[c] == nums[c+1]) c--;
17                     else{
18                         result.push_back({nums[a], nums[b], nums[c]});
19                         b++;
20                         c--;
21                     }
22                 }
23             }
24         }
25         sort(result.begin(), result.end());
26         return result;
27     }
28 };

 

 

3Sum

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4494342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!