LeetCode 18. 4Sum(四数之和)

308 阅读1分钟

leetcode.com/problems/4s…

Discuss:www.cnblogs.com/grandyang/p…

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

0 <= a, b, c, d < n a, b, c, and d are distinct. nums[a] + nums[b] + nums[c] + nums[d] == target You may return the answer in any order.

Example 1:

Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Example 2:

Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]

Constraints:

  • 1 <= nums.length <= 200

  • -109 <= nums[i] <= 109

  • -109 <= target <= 109

解法一:

此题与 Three Sum 类似,就是多了一层循环,手动进行去重复处理。主要可以进行的有三个地方,首先在两个 for 循环下可以各放一个,因为一旦当前的数字跟上面处理过的数字相同了,那么找下来肯定还是重复的。之后就是当 sum 等于 target 的时候了,在将四个数字加入结果 res 之后,left 和 right 都需要去重复处理,分别向左右方向遍历即可。

class Solution {
    fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
        if (nums.size < 4) {
            return mutableListOf()
        }
        val result = mutableListOf<List<Int>>()
        nums.sort()
        for (i in 0..nums.size - 4) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue
            }
            for (j in i + 1..nums.size - 3) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue
                }
                var left = j + 1
                var right = nums.size - 1
                while (left < right) {
                    val sum = nums[i] + nums[j] + nums[left] + nums[right]
                    if (sum == target) {
                        val item = mutableListOf(nums[i], nums[j], nums[left], nums[right])
                        result.add(item)
                        while (left < right && nums[left] == nums[left + 1]) {
                            ++left
                        }
                        while (left < right && nums[right] == nums[right - 1]) {
                            --right
                        }
                        ++left
                        --right
                    } else if (sum < target) {
                        ++left
                    } else {
                        --right
                    }
                }
            }
        }
        return result
    }
}