LeetCode 15. 3Sum

来源:互联网 发布:可以赚钱的app软件 编辑:程序博客网 时间:2024/05/20 01:47

15. 3Sum

题目描述

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: 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 使得他们的和等于0。 找出数组中所有能够满足这样条件的三元组。(重复的三元组只统计一次)。

这种满足指定和的题目,第一个想法是采用循环去做。但如果直接嵌套循环,复杂度太大。一种处理此类问题的方式是 two pointers。先固定一个数后,还需要2个数。前后固定两个指针,在一个有序的数组中,不停的移动指针,沿途将满足条件的结果存入,知道前后两个指针相遇则停止遍历。

class Solution {public:    vector<vector<int>> threeSum(vector<int>& nums) {        if (nums.empty() || nums.size() < 3) return {};        sort(nums.begin(), nums.end());        vector<vector<int>> ret;        for (int i = 0; i < nums.size()-2; i++) {            int l = i+1;            int r = nums.size() - 1;            if (i == 0 || (i > 0 && nums[i] != nums[i-1])){ //  注意此处的去重条件                while (l < r) {                    int sum = nums[i] + nums[l] + nums[r];                    if (sum == 0) {                        ret.push_back({nums[i], nums[l], nums[r]});                        while (l+1 < r && nums[l]  == nums[l+1]) l++;                        while(l < r-1 && nums[r] == nums[r-1]) r--;                        l++;                        r--;                    }                    else if (sum < 0) {                        l++;                    }                    else if (sum > 0) {                        r--;                    }                }            }        }        return ret;    }};

if (i == 0 || (i > 0 && nums[i] != nums[i-1]){}

分析这个条件:
已知数组是有序的。

  • 当 i=0 时,第一次遍历,肯定要去扫描数据;
  • 当 i>0 时,由于数据是有序的,所以首数字 nums[i] 决定了结果的差异。如果前后相邻的两个 nums[i] 是相同的,则他们产生的结果也会相同的

    补充:可以将三个数的和扩展到求 4个数的和等于指定数 的问题。
    这个在 leetcode 上也有对应的题目 4sum 如下:

    https://leetcode.com/problems/4sum/description/

原创粉丝点击