【Leetcode】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)

 1 class Solution {
 2 public:
 3     vector<vector<int> > threeSum(vector<int> &num) {
 4         vector<vector<int>> result;
 5         if (num.size() < 3) return result;
 6         sort(num.begin(), num.end());
 7         for (size_t i = 0; i < num.size() - 2; ++i) {
 8             if (i > 0 && num[i] == num[i - 1]) continue;
 9             size_t j = i + 1, k = num.size() - 1;
10             while (j < k) {
11                 if (j > i + 1 && num[j] == num[j - 1]) {
12                     ++j;
13                     continue;
14                 }
15                 if (k < num.size() - 1 && num[k] == num[k + 1]) {
16                     --k;
17                     continue;
18                 }
19                 int sum = num[i] + num[j] + num[k];
20                 if (sum == 0) {
21                     result.push_back({num[i], num[j], num[k]});
22                     ++j;
23                     --k;
24                 } else if (sum < 0) {
25                     ++j;
26                 } else {
27                     --k;
28                 }
29             }
30         }
31         return result;
32     }
33 };
View Code

先排序,再左右夹逼查找。输出要求不重复,所以需要进行一些剪枝处理。

posted @ 2014-03-17 13:45  小菜刷题史  阅读(126)  评论(0编辑  收藏  举报