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

3Sum

时间:2016-06-21 10:42:26      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

1、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: 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]
]

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
    vector<vector<int>> triples;
    sort(nums.begin(), nums.end());
    int i = 0, last = nums.size() - 1;
    while (i < last) {
        int a = nums[i], j = i+1, k = last;    // 先选中一个,然后后面的找两个值
        while (j < k) {
            int b = nums[j], c = nums[k], sum = a+b+c;
            if (sum == 0) triples.push_back({a, b, c});   // 使用了vector的初始化{a, b, c}
            if (sum <= 0) while (nums[j] == b && j < k) j++;    // 这个厉害,可以使用在判断相等的时候一直往前
            if (sum >= 0) while (nums[k] == c && j < k) k--;
        }
        while (nums[i] == a && i < last) i++;
    }
    return triples;
    }
};

 

3Sum

标签:

原文地址:http://www.cnblogs.com/dylqt/p/5602606.html

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