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

Function threeSum

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

Source from the content-addressed store, hash-verified

3import "sort"
4
5func threeSum(nums []int) [][]int {
6 triplets := make([][]int, 0)
7 sort.Ints(nums)
8
9 if len(nums) < 3 {
10 return triplets
11 }
12
13 // pick a number, then solve the two sum problem in the space in front of it
14 for i := 0; i < len(nums); i++ {
15 // skip duplicates of the starting number if we've seen it in the past
16 if i > 0 && nums[i] == nums[i-1] {
17 continue
18 }
19
20 // determine what is needed from two sum
21 need := 0 - nums[i]
22 start := i + 1
23 end := len(nums) - 1
24 for start < end {
25 // if we've found what we need
26 if nums[start]+nums[end] == need {
27 triplets = append(triplets, []int{nums[i], nums[start], nums[end]})
28
29 // Choose to skip duplicates on one end or the other (start or end)
30 // In my first answer below, I skipped duplicates from start, for example.
31 // We need to continue to search in the space in between start and end
32 // for more sums that equal need. So, we need to move one end forward
33 // and skip duplicates in order to satisfy the 'unique' requirement of
34 // the problem.
35 end--
36 for start < end && nums[end] == nums[end+1] {
37 end--
38 }
39 } else if nums[start]+nums[end] > need {
40 end--
41 } else {
42 start++
43 }
44 }
45 }
46
47 return triplets
48}
49
50func threeSum0(nums []int) [][]int {
51 triplets := make([][]int, 0)

Callers 1

Test_threeSumFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_threeSumFunction · 0.68