-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0018_4sum.swift
32 lines (27 loc) · 962 Bytes
/
0018_4sum.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// https://leetcode.com/problems/4sum/
class Solution {
func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] {
guard nums.count >= 4 else { return [] }
var result = Set<[Int]>()
let sortedNums = nums.sorted()
for i in 0..<(nums.count - 3) {
for j in (i + 1)..<(nums.count - 2) {
var l = j + 1
var r = nums.count - 1
while l < r {
let sum = sortedNums[i] + sortedNums[j] + sortedNums[l] + sortedNums[r]
if sum == target {
result.insert([sortedNums[i], sortedNums[j], sortedNums[l], sortedNums[r]])
l += 1
r -= 1
} else if sum < target {
l += 1
} else {
r -= 1
}
}
}
}
return Array(result)
}
}