Algorithm
Leet Code Medium
[Swift] 3Sum
[Swift] 3Sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j, i != k, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = []
Output: []
Example 3:
Input: nums = [0]
Output: []
Constraints:
- 0 <= nums.length <= 3000
- $-10^5$ <= nums[i] <= $10^5$
문제 이해
코드
func threeSum(_ nums: [Int]) -> [[Int]] {
let nums = nums.sorted()
var set = Set<[Int]>()
for i in 0 ..< nums.count {
var left = i + 1
var right = nums.count - 1
while left < right {
if nums[i] + nums[left] + nums[right] == 0 {
set.insert([nums[i], nums[left], nums[right]])
left += 1
right -= 1
} else if nums[i] + nums[left] + nums[right] < 0 {
left += 1
} else if nums[i] + nums[left] + nums[right] > 0 {
right -= 1
}
}
}
return Array(set)
}
풀이
-
다른 분의 멋진 코드
잘 배웠습니다.
-
댓글남기기