Skip to content

Commit b1fa72f

Browse files
committed
Add 15. 3SUm
1 parent c430fe9 commit b1fa72f

File tree

3 files changed

+89
-0
lines changed

3 files changed

+89
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,12 @@ If you only want to run tests in a specific problem `(e.g., ./easy/0001_two_sum)
2626
go test ./easy/0001_two_sum
2727
```
2828

29+
Clean test cache
30+
31+
```bash
32+
go clean -testcache
33+
```
34+
2935
## Solutions (Continue Updating...)
3036

3137
| Leetcode ID | Title & Solution | Coefficient Of Difficulty | Remarks | Approach |

medium/15_3sum/15_3sum.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package three_sum
2+
3+
import "sort"
4+
5+
func ThreeSum(nums []int) [][]int {
6+
res := make([][]int, 0)
7+
8+
//sort in asc
9+
sort.Slice(nums, func(i , j int) bool {
10+
return nums[i] < nums[j]
11+
})
12+
13+
for i := range nums {
14+
if i > 0 && nums[i] == nums[i - 1] {
15+
continue
16+
}
17+
18+
target := -nums[i]
19+
j := i + 1
20+
k := len(nums) - 1
21+
22+
for j < k {
23+
if target == nums[j] + nums[k] {
24+
res = append(res, []int{nums[i], nums[j], nums[k]})
25+
26+
for j < k && nums[j] == nums[j + 1] {
27+
j++
28+
}
29+
for j < k && nums[k] == nums[k - 1] {
30+
k--
31+
}
32+
33+
j ++
34+
k --
35+
} else if target > nums[j] + nums[k] {
36+
j ++
37+
} else {
38+
k --
39+
}
40+
}
41+
}
42+
43+
return res
44+
}

medium/15_3sum/15_3sum_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package three_sum
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
func TestThreeSum(t *testing.T) {
9+
tests := []struct {
10+
name string
11+
nums []int
12+
expectedResult [][]int
13+
} {
14+
{
15+
name: "Test Case 1",
16+
nums: []int{-1,0,1,2,-1,-4},
17+
expectedResult: [][]int{{-1,-1,2}, {-1,0,1}},
18+
},
19+
{
20+
name: "Test Case 2",
21+
nums: []int{0,1,1},
22+
expectedResult: [][]int{},
23+
},
24+
{
25+
name: "Test Case 3",
26+
nums: []int{0,0,0},
27+
expectedResult: [][]int{{0,0,0}},
28+
},
29+
}
30+
31+
for _, test := range tests {
32+
t.Run(test.name, func(t *testing.T) {
33+
got := ThreeSum(test.nums)
34+
if !reflect.DeepEqual(got, test.expectedResult) {
35+
t.Errorf("3Sum(%v) = %v, want = %v", test.nums, got, test.expectedResult)
36+
}
37+
})
38+
}
39+
}

0 commit comments

Comments
 (0)