18. 4Sum

复制代码
package LeetCode_18

/**
 * 18. 4Sum
 * https://leetcode.com/problems/4sum/
 * Given an array nums of n integers and an integer target,
 * are there elements a, b, c, and d in nums such that a + b + c + d = target?
 * Find all unique quadruplets in the array which gives the sum of target.
Notice that the solution set must not contain duplicate quadruplets.
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 = [], target = 0
Output: []

Constraints:
1. 0 <= nums.length <= 200
2. -109 <= nums[i] <= 109
3. -109 <= target <= 109
 * */
class Solution {
    /*
    * solution: base on 3Sum, Time:O(n^3), Space:O(1)
    * */
    fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
        val result = ArrayList<ArrayList<Int>>()
        if (nums.size < 4) {
            return result
        }
        nums.sort()
        val n = nums.size
        for (i in 0 until n - 3) {
            //avoid duplicate
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue
            }
            for (j in i + 1 until n - 2) {
                //avoid duplicate
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue
                }
                var left = j + 1
                var right = n - 1
                while (left < right) {
                    val sum = nums[i] + nums[j] + nums[left] + nums[right]
                    if (sum == target) {
                        //find out one result
                        result.add(arrayListOf(nums[i], nums[j], nums[left], nums[right]))
                        //avoid duplicate
                        while (left < right && nums[left] == nums[left + 1]) {
                            left++
                        }
                        while (left < right && nums[right] == nums[right - 1]) {
                            right--
                        }
                        left++
                        right--
                    } else if (sum < target) {
                        //if sum less than target, we need more large number, so left++, because array was sorted
                        left++
                    } else {
                        right--
                    }
                }
            }
        }
        return result
    }
}
复制代码

 3Sum

posted @   johnny_zhao  阅读(91)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-12-19 112. Path Sum
点击右上角即可分享
微信分享提示