[leetcode][15] 3Sum

Posted ekoeko

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode][15] 3Sum相关的知识,希望对你有一定的参考价值。

15. 3Sum

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

解析

从给定的数组里面找到三个数之和等于0,返回所有的结果集,去重。

参考答案(没做出来)

public List<List<Integer>> threeSum(int[] num) {
    Arrays.sort(num);
    List<List<Integer>> res = new LinkedList<>(); 
    for (int i = 0; i < num.length-2; i++) {
        if (i == 0 || (i > 0 && num[i] != num[i-1])) {
            int lo = i+1, hi = num.length-1, sum = 0 - num[i];
            while (lo < hi) {
                if (num[lo] + num[hi] == sum) {
                    res.add(Arrays.asList(num[i], num[lo], num[hi]));
                    while (lo < hi && num[lo] == num[lo+1]) lo++;
                    while (lo < hi && num[hi] == num[hi-1]) hi--;
                    lo++; hi--;
                } else if (num[lo] + num[hi] < sum) lo++;
                else hi--;
           }
        }
    }
    return res;
}

这里主要是去重比较麻烦,所以这里选择了先排序,然后用双指针遍历,再把相邻重复的元素的忽略掉。

以上是关于[leetcode][15] 3Sum的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 15 3Sum

[leetcode][15] 3Sum

Leetcode 15. 3Sum(python)

Leetcode 15. 3Sum

leetcode15 3Sum

[leetcode]15. 3Sum[UNSOLVED]