leetcode15. 三数之和
题目描述:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
代码模版(swift)
class Solution {
func threeSum(_ nums: [Int]) -> [[Int]] {
}
}
解法1(三趟遍历)
直观的 我们可以每次执行确定一个数,然后再确定一个数,然后继续遍历剩下的数,找到三个数相加为目标数那三个数
代码不再赘述
-
空间复杂度:O(1)
-
时间复杂度:O(n^3)
解法2(一趟遍历+双指针)
思路:
先排序,然后在第一趟遍历的时候确定一个数,然后维护双指针,一个在第一个数下一个数,一个在最后一个数,确定左指针位置,因为数据已被排列,右指针左移,如果移动下去没有答案并且大于和值,移动左指针。因为存在相同的数,去重操作跳过这个数即可。
class Solution {
func threeSum(_ nums: [Int]) -> [[Int]] {
var array = nums
let n = array.count
array.sort() // 排序
var ans = [[Int]].init()
for first in 0..<n {
if first > 0 && array[first] == array[first - 1] { // 去重操作,跳过该循环
continue
}
var third = n - 1 // 右指针
let target = -array[first]
for second in first+1..<n { // 移动左指针操作
if second > first + 1 && array[second] == array[second - 1] { // 大于目标和情况移动左指针,去重操作
continue
}
while second < third && array[second] + array[third] > target { // 移动右指针
third -= 1
}
if second == third { // 两指针相遇
break
}
if array[second] + array[third] == target { // 找到目标和,存在答案数组中
ans.append([array[first], array[second], array[third]])
}
}
}
return ans
}
}
-
空间复杂度:O(1)
-
时间复杂度:O(n^2) 本文正在参与「掘金 2021 春招闯关活动」, 点击查看活动详情