给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
结果
执行用时:3352 ms, 在所有 Swift 提交中击败了5.00%的用户
内存消耗:18.4 MB, 在所有 Swift 提交中击败了55.27%的用户
思路
第一次,暴力解法,直接超时
第二次,先排序再双指针,也只是勉强通过而已
代码
class Solution {
func threeSum(_ nums: [Int]) -> [[Int]] {
guard nums.count > 2 else { return [] }
var resultArray: [[Int]] = []
var resultSet: Set<Set<Int>> = []
let sortedNums = nums.sorted()
for i in 0..<sortedNums.count - 2 {
let first = sortedNums[i]
var numsDic: [Int: Int] = [:]
var low = i + 1, high = sortedNums.count - 1
while low < high {
let second = sortedNums[low]
let third = sortedNums[high]
if first + second + third == 0 {
if !resultSet.contains([first, second, third]) {
resultArray.append([first, second, third])
resultSet.insert([first, second, third])
}
low = low + 1
} else if first + second + third > 0 {
high = high - 1
} else {
low = low + 1
}
}
}
return resultArray
}
}
网友评论