LeetCode每日一题:three sum

2017-07-05  本文已影响22人  yoshino

问题描述

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:
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)

问题分析

三个数之和,我们可以利用一个外循环变成两个数之和,注意数组间的重复问题即可。

代码实现

public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if (num.length < 3) return result;
        Arrays.sort(num);
        for (int i = 0; i < num.length - 2; i++) {
            if (i == 0 || (i > 0 && num[i] != num[i - 1])) {
                int left = i + 1, right = num.length - 1, sum = 0 - num[i];
                while (left < right) {
                    if (num[left] + num[right] == sum) {
                        ArrayList<Integer> list = new ArrayList<>();
                        list.add(num[i]);
                        list.add(num[left]);
                        list.add(num[right]);
                        result.add(list);
                        left++;
                        right--;
                        while (left < right && num[left] == num[left - 1]) left++;
                        while (right > left && num[right] == num[right + 1]) right--;
                    } else if (num[left] + num[right] > sum) right--;
                    else left++;
                }
            }
        }
        return result;
    }
上一篇下一篇

猜你喜欢

热点阅读