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

[LeetCode] 15. 3Sum 三数之和

时间:2018-03-03 10:59:51      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:begin   cpp   uniq   相等   nts   get   not   target   左移   

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)

 

先对数组排序,然后遍历排序后的数组, 用0减去当前数得到target,然后对后面的数使用双指针,left和right分别指向第一个和最后一个,看这两个指针指向的数相加是否为之前得到的数target,如果相等就找到一组添加到结果中,如果小于left指针右移1位,如果大于,right指针左移1位,然后在相加比较。对于重复的数字可以用while循环跳过。

C++:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());
        for (int k = 0; k < nums.size(); ++k) {
            if (nums[k] > 0) break;
            if (k > 0 && nums[k] == nums[k - 1]) continue;
            int target = 0 - nums[k];
            int i = k + 1, j = nums.size() - 1;
            while (i < j) {
                if (nums[i] + nums[j] == target) {
                    res.push_back({nums[k], nums[i], nums[j]});
                    while (i < j && nums[i] == nums[i + 1]) ++i;
                    while (i < j && nums[j] == nums[j - 1]) --j;
                    ++i; --j;
                } else if (nums[i] + nums[j] < target) ++i;
                else --j;
            }
        }
        return res;
    }
};

 

  

[LeetCode] 15. 3Sum 三数之和

标签:begin   cpp   uniq   相等   nts   get   not   target   左移   

原文地址:https://www.cnblogs.com/lightwindy/p/8495665.html

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