zoukankan      html  css  js  c++  java
  • LeetCode #18 4Sum

    LeetCode #18 4Sum

    Question

    Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

    Note: The solution set must not contain duplicate quadruplets.

    For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
    A solution set is:
    [
      [-1,  0, 0, 1],
      [-2, -1, 1, 2],
      [-2,  0, 0, 2]
    ]
    

    Solution

    Approach #1

    class Solution {
        func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] {
            if nums.count < 4 { return [] }
            let sortedNums = nums.sorted()
            var results: [[Int]] = []
            for i in 0..<sortedNums.count - 3 {
                if i > 0, sortedNums[i] == sortedNums[i - 1] { continue }
                for j in i + 1..<sortedNums.count - 2 {
                    if j > i + 1, sortedNums[j] == sortedNums[j - 1] { continue }
                    var l = j + 1
                    var r = sortedNums.count - 1
                    while l < r {
                        let sum = sortedNums[i] + sortedNums[j] + sortedNums[l] + sortedNums[r]
                        if sum == target {
                            results.append([sortedNums[i], sortedNums[j], sortedNums[l], sortedNums[r]])
                            while l < r, sortedNums[l] == sortedNums[l + 1] { l += 1 }
                            l += 1
                            while l < r, sortedNums[r] == sortedNums[r - 1] { r -= 1 }
                            r -= 1
                        } else if sum < target {
                            while l < r, sortedNums[l] == sortedNums[l + 1] { l += 1 }
                            l += 1
                        } else {
                            while l < r, sortedNums[r] == sortedNums[r - 1] { r -= 1 }
                            r -= 1
                        }
                    }
                }
            }
            return results
        }
    }
    

    Time complexity: O(n^3).

    Space complexity: O(n).

    转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6893639.html

  • 相关阅读:
    js小程序
    事务的概念
    为期一个月培训的总结
    软件测试培训总结篇2
    软件测试培训总结篇1
    软件测试培训第30天
    软件测试培训第29天
    软件测试培训第28天
    软件测试培训第26天
    软件测试培训第27天
  • 原文地址:https://www.cnblogs.com/silence-cnblogs/p/6893639.html
Copyright © 2011-2022 走看看