Skip to content

Commit 75fbbbd

Browse files
author
openset
committed
Add: 3Sum Closest
1 parent 03b18e3 commit 75fbbbd

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-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: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,25 @@
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+
for _, tc := range tests {
20+
output := threeSumClosest(tc.input, tc.target)
21+
if output != tc.expected {
22+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
23+
}
24+
}
25+
}

0 commit comments

Comments
 (0)