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 7ed025a

Browse files
author
openset
committed
Add: 3Sum
1 parent 2fd3e85 commit 7ed025a

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-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: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,40 @@
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+
input: []int{-2, 0, 0, 2, 2},
29+
expected: [][]int{
30+
{-2, 0, 2},
31+
},
32+
},
33+
}
34+
for _, tc := range tests {
35+
output := threeSum(tc.input)
36+
if !reflect.DeepEqual(output, tc.expected) {
37+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
38+
}
39+
}
40+
}

0 commit comments

Comments
(0)

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