Skip to content

Commit e6a08cf

Browse files
committed
solve 3Sum
1 parent b8af01d commit e6a08cf

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

3sum/delight010.swift

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
func threeSum(_ nums: [Int]) -> [[Int]] {
3+
let nums = nums.sorted()
4+
var answer: Set<[Int]> = []
5+
for (index, num) in nums.enumerated() {
6+
var leftIndex = index + 1
7+
var rightIndex = nums.endIndex - 1
8+
while leftIndex < rightIndex {
9+
let sum = num + nums[leftIndex] + nums[rightIndex]
10+
if sum == 0 {
11+
answer.insert([num, nums[leftIndex], nums[rightIndex]])
12+
leftIndex += 1
13+
rightIndex -= 1
14+
} else if sum < 0 {
15+
leftIndex += 1
16+
} else if sum > 0 {
17+
rightIndex -= 1
18+
}
19+
}
20+
}
21+
22+
return Array(answer)
23+
}
24+
}
25+

0 commit comments

Comments
 (0)