[LeetCode]--15. 3Sum

来源:互联网 发布:html5 棋牌游戏源码 编辑:程序博客网 时间:2024/04/28 13:16

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]]

给一组数组,要求得出所有和为0的数字组合,要求数字组合不能重复出现,并且按照升序排列。
先对数组进行排序,时间复杂度O(log(n)),然后定好一个数的位置,查找另外两个数的和等于-nums[i]的组合,由于数组排好序了,所以可以从两边往中间走,当结果大于0的时候后边往后退一步,否则前边进一步,时间复杂度O(n^2),所以时间复杂度为O(n^2)。

public List<List<Integer>> threeSum(int[] nums) {        List<List<Integer>> res = new ArrayList<List<Integer>>();        int len = nums.length;        if (len < 3)            return res;        Arrays.sort(nums);        for (int i = 0; i < len; i++) {            if (nums[i] > 0)                break;            if (i > 0 && nums[i] == nums[i - 1])                continue;            int begin = i + 1, end = len - 1;            while (begin < end) {                int sum = nums[i] + nums[begin] + nums[end];                if (sum == 0) {                    List<Integer> list = new ArrayList<Integer>();                    list.add(nums[i]);                    list.add(nums[begin]);                    list.add(nums[end]);                    res.add(list);                    begin++;                    end--;                    while (begin < end && nums[begin] == nums[begin - 1])                        begin++;                    while (begin < end && nums[end] == nums[end + 1])                        end--;                } else if (sum > 0)                    end--;                else                    begin++;            }        }        return res;    }
0 0
原创粉丝点击