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