Skip to content

Commit 06d2d71

Browse files
author
Shuo
authored
Merge pull request #613 from openset/develop
Add: 3Sum Closest
2 parents e4dff27 + f0db80f commit 06d2d71

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,31 @@
11
package p_3sum_closest
2+
3+
import (
4+
"math"
5+
"sort"
6+
)
7+
8+
func threeSumClosest(nums []int, target int) int {
9+
sort.Ints(nums)
10+
ans, diff, n := math.MaxInt32, math.MaxInt32, len(nums)
11+
for i := 0; i < n-2; i++ {
12+
l, r := i+1, n-1
13+
for l < r {
14+
sum := nums[i] + nums[l] + nums[r]
15+
if sum < target {
16+
if target-sum < diff {
17+
ans, diff = sum, target-sum
18+
}
19+
l++
20+
} else if sum > target {
21+
if sum-target < diff {
22+
ans, diff = sum, sum-target
23+
}
24+
r--
25+
} else {
26+
return target
27+
}
28+
}
29+
}
30+
return ans
31+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,45 @@
11
package p_3sum_closest
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
target int
8+
expected int
9+
}
10+
11+
func TestThreeSumClosest(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
input: []int{-1, 2, 1, -4},
15+
target: 1,
16+
expected: 2,
17+
},
18+
{
19+
input: []int{-1, 0, 1, 2, -1, -4},
20+
target: 1,
21+
expected: 1,
22+
},
23+
{
24+
input: []int{0, 0, 0, 0},
25+
target: 1,
26+
expected: 0,
27+
},
28+
{
29+
input: []int{-2, 0, 0, 2, 2, 2},
30+
target: 2,
31+
expected: 2,
32+
},
33+
{
34+
input: []int{-2, 0, 0, 2, 2, 2, 2},
35+
target: 1,
36+
expected: 0,
37+
},
38+
}
39+
for _, tc := range tests {
40+
output := threeSumClosest(tc.input, tc.target)
41+
if output != tc.expected {
42+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)