15. 3 sum

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

曾经使用Arrays.binarySearch(nums,target);但是如果数组中有重复的target的时候,返回的标号是不确定的
难点在于返回的数组列表里不能有重复的解
对于重复元素太多的情况,可以考虑在初始化时将其去掉,但是要注意把含有重复元素的解加入rst。

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> rst = new ArrayList<List<Integer>>();
        if (nums == null || nums.length == 0) {
            return rst;
        }
        Arrays.sort(nums);
        for (int a = 0; a < nums.length - 2; a++) {
            if (a != 0 && nums[a] == nums[a - 1]) {
                continue;
            }
            int target = -nums[a];
            int b = a + 1;
            int c = nums.length - 1;
            while (b < c) {
                int sum = nums[b] + nums[c];
                if (sum == target) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[a]);
                    list.add(nums[b]);
                    list.add(nums[c]);
                    rst.add(list);
                    b++;
                    c--;
                    while (b < c && nums[b] == nums[b - 1]) {
                        b++;                        
                    }
                    while (b < c && nums[c] == nums[c + 1]) {
                        c--; 
                    }
                } else if (sum < target) {
                    b++;
                } else {
                    c--;
                }
            }
        }
        return rst;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42521881/article/details/85273332