[LeetCode] 15. 3Sum
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
Analyse:
Solution:
class Solution {
func threeSum(_ nums: [Int]) -> [[Int]] {
var output: [[Int]] = [];
var sortedNums = nums.sorted{$0 < $1}
var i = 0
while (i < sortedNums.count - 2) {
let value = sortedNums[i]
var left = i + 1
var right = sortedNums.count - 1
while(left < sortedNums.count && right > 0 && left < right) {
let sum = value + sortedNums[left] + sortedNums[right]
if (sum == 0) {
output.append([sortedNums[left], sortedNums[right], value])
repeat {
left += 1
} while(left < right && sortedNums[left] == sortedNums[left - 1])
repeat {
right -= 1
} while(left < right && sortedNums[right] == sortedNums[right + 1])
} else if(sum < 0) {
left += 1
} else {
right -= 1
}
}
repeat {
i += 1
}
while((i < (sortedNums.count - 2)) && (sortedNums[i] == sortedNums[i - 1]))
}
return output
}
}
Last updated