Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b7f67a5

Browse files
author
Shuo
authored
Merge pull request #603 from openset/develop
Add: 3Sum
2 parents 9ad583d + bd54c0a commit b7f67a5

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

‎problems/3sum/3sum.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,31 @@
11
package p_3sum
2+
3+
import "sort"
4+
5+
func threeSum(nums []int) [][]int {
6+
sort.Ints(nums)
7+
ans, length := make([][]int, 0), len(nums)
8+
for i := 0; i < length-2; i++ {
9+
if nums[i] <= 0 && (i == 0 || nums[i] != nums[i-1]) {
10+
l, r := i+1, length-1
11+
for l < r {
12+
sum := nums[i] + nums[l] + nums[r]
13+
if sum < 0 {
14+
l++
15+
} else if sum > 0 {
16+
r--
17+
} else {
18+
ans = append(ans, []int{nums[i], nums[l], nums[r]})
19+
l, r = l+1, r-1
20+
for l < r && nums[l] == nums[l-1] {
21+
l++
22+
}
23+
for l < r && nums[r] == nums[r+1] {
24+
r--
25+
}
26+
}
27+
}
28+
}
29+
}
30+
return ans
31+
}

‎problems/3sum/3sum_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,47 @@
11
package p_3sum
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input []int
10+
expected [][]int
11+
}
12+
13+
func TestThreeSum(t *testing.T) {
14+
tests := [...]caseType{
15+
{
16+
input: []int{-1, 0, 1, 2, -1, -4},
17+
expected: [][]int{
18+
{-1, -1, 2},
19+
{-1, 0, 1},
20+
},
21+
},
22+
{
23+
input: []int{0, 0, 0, 0},
24+
expected: [][]int{
25+
{0, 0, 0},
26+
},
27+
},
28+
{
29+
input: []int{-2, 0, 0, 2, 2, 2},
30+
expected: [][]int{
31+
{-2, 0, 2},
32+
},
33+
},
34+
{
35+
input: []int{-2, 0, 0, 2, 2, 2, 2},
36+
expected: [][]int{
37+
{-2, 0, 2},
38+
},
39+
},
40+
}
41+
for _, tc := range tests {
42+
output := threeSum(tc.input)
43+
if !reflect.DeepEqual(output, tc.expected) {
44+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
45+
}
46+
}
47+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /