forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWhiteHyun.swift
More file actions
41 lines (34 loc) ยท 877 Bytes
/
WhiteHyun.swift
File metadata and controls
41 lines (34 loc) ยท 877 Bytes
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
33
34
35
36
37
38
39
40
41
//
// 15. 3Sum
// https://leetcode.com/problems/3sum/description/
// Dale-Study
//
// Created by WhiteHyun on 2024/06/04.
//
class Solution {
func threeSum(_ nums: [Int]) -> [[Int]] {
var result: [[Int]] = []
let sorted = nums.sorted()
for (index, element) in sorted.enumerated() where index <= 0 || element != sorted[index - 1] {
var left = index + 1
var right = sorted.count - 1
while left < right {
let threeSum = element + sorted[left] + sorted[right]
if threeSum > 0 {
right -= 1
continue
}
if threeSum < 0 {
left += 1
continue
}
result.append([element, sorted[left], sorted[right]])
left += 1
while sorted[left] == sorted[left - 1] && left < right {
left += 1
}
}
}
return result
}
}