MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / threeSum0

Function threeSum0

three_sum_15/solution.go:50–88  ·  view source on GitHub ↗
(nums []int)

Source from the content-addressed store, hash-verified

48}
49
50func threeSum0(nums []int) [][]int {
51 triplets := make([][]int, 0)
52 if len(nums) < 3 {
53 return triplets
54 }
55
56 sort.Ints(nums)
57 for i := 0; i < len(nums)-2; i++ {
58 j := i + 1
59 k := len(nums) - 1
60 if i != 0 && nums[i] == nums[i-1] {
61 continue
62 }
63
64 for j < k {
65 tripletSum := nums[i] + nums[j] + nums[k]
66 if tripletSum == 0 {
67 triplets = append(triplets, []int{nums[i], nums[j], nums[k]})
68 j++
69
70 // We found the sum we wanted, and moved j forward one index.
71 // If the value at j is equal to the value at j-1, a duplicate
72 // will be produced. Continue to move j forward until a new value
73 // is seen or j >= k.
74 for j < k && nums[j] == nums[j-1] {
75 j++
76 }
77 } else if tripletSum < 0 {
78 // If tripletSum is less than 0, we must increase the sum
79 j++
80 } else {
81 // If tripletSum is less than 0, we must decrease the sum
82 k--
83 }
84 }
85 }
86
87 return triplets
88}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected