【LeetCode】15. 3Sum - Java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoguaihai/article/details/84197469

1. 题目描述:

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

2. 思路分析:

题目的意思是找到数组中所有3个和为0的数,并且不能重复。

该题可以转化成Two Sum的思路去解决。先固定一个数,然后从数组中剩下的数中查找和为该数负值(target)得2个数,则转化成了Two Sum问题:先排序数组,使两个指针分别指向首尾的两个数,如果这两个数和等于target,则找到,如果小于target则右移左指针,如果大于target则左移右指针。

关键是题目要求去重,所以每次移动指针的时候要判断一下是否和上一个数相同,如果相同则继续移动。

3. Java代码:

源代码见我GiHub主页

代码:

public static List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> result = new ArrayList<>();
    Arrays.sort(nums);
    for (int i = 0; i < nums.length; i++) {
        // 用于去重
        if (i != 0 && nums[i] == nums[i - 1]) {
            continue;
        }

        // 转化成Two Sum 问题
        int target = -nums[i];
        int left = i + 1;
        int right = nums.length - 1;
        while (left < right) {
            int sum = nums[left] + nums[right];
            if (sum == target) {
                List<Integer> triplets = Arrays.asList(nums[i], nums[left], nums[right]);
                result.add(triplets);
                left++;
                right--;

                // 用于去重
                while (left < right && nums[left] == nums[left - 1]) {
                    left++;
                }
                while (left < right && nums[right] == nums[right + 1]) {
                    right--;
                }

            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
    }
    return result;
}

猜你喜欢

转载自blog.csdn.net/xiaoguaihai/article/details/84197469
今日推荐