15. 3Sum
package main
import (
"sort"
)
func threeSum(nums []int) [][]int {
sort.Ints(nums) // Sort the slice in place
var res [][]int
for i := 0; i < len(nums)-2; i++ {
// Skip duplicate values for i
if i > 0 && nums[i] == nums[i-1] {
continue
}
for j, k := i+1, len(nums)-1; j < k; {
sum := nums[i] + nums[j] + nums[k]
if sum > 0 {
k--
} else if sum < 0 {
j++
} else {
// Append the triplet
res = append(res, []int{nums[i], nums[j], nums[k]})
// Skip duplicate values for j and k
for j < k && nums[j] == nums[j+1] {
j++
}
for j < k && nums[k] == nums[k-1] {
k--
}
j++
k--
}
}
}
return res
}
Time Complexity
Combining both parts, the dominant term for the time complexity is O(n2), making the overall time complexity of the threeSum algorithm O(nlogn)+O(n2)=O(n2). The sorting term O(nlogn) is overshadowed by the O(n2) complexity of the nested loop search.
领英推荐
Space Complexity
Thus, the overall space complexity of the algorithm is O(m)+O(logn), where m is the space required for the output. Since m can vary independently of n, and the O(logn) term is related to the sorting algorithm's space requirement, it's more precise to note that the significant factor here is the space required to store the result, making the space complexity O(m) for the output list, with an additional O(logn) space for the sorting operation.