Skip to content

Commit e713c94

Browse files
committed
16. 3 sum closest
1 parent 6a6e48e commit e713c94

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

16.3-sum-closest.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package leetcode
2+
3+
import (
4+
"math"
5+
"sort"
6+
)
7+
8+
/*
9+
* @lc app=leetcode id=16 lang=golang
10+
*
11+
* [16] 3Sum Closest
12+
*/
13+
14+
// @lc code=start
15+
func threeSumClosest(nums []int, target int) int {
16+
sort.Ints(nums)
17+
ans := nums[0] + nums[1] + nums[2]
18+
19+
for i := 0; i < len(nums); i++ {
20+
left, right := i+1, len(nums)-1
21+
for left < right {
22+
sum := nums[i] + nums[left] + nums[right]
23+
if math.Abs(float64(sum-target)) < math.Abs(float64(ans-target)) {
24+
ans = sum
25+
}
26+
27+
if target < sum {
28+
right--
29+
} else if target > sum {
30+
left++
31+
} else {
32+
return ans
33+
}
34+
}
35+
}
36+
37+
return ans
38+
}
39+
40+
// @lc code=end

0 commit comments

Comments
 (0)