• 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

  • 相关阅读:
    apue第16章笔记
    重构与重写
    架构方面的笔记
    多进程失败拉起的demo
    Elasticsearch match_phrase用法
    c++风格
    cocos2d-x 3.2 移植到android
    Mac 下配置 Cocos2d-x 3-x android 的环境
    解决最新版的ADT没有NDK选项的问题
    待飞日记(第六天和第七天)
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14159103.html
Copyright © 2020-2023  润新知