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 @ 2020-12-19 14:51  johnny_zhao  阅读(90)  评论(0编辑  收藏  举报