-
Notifications
You must be signed in to change notification settings - Fork 0
/
16.go
41 lines (35 loc) · 857 Bytes
/
16.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main
import (
"math"
"sort"
)
func threeSumClosest(nums []int, target int) int {
var result int
closest := math.Inf(1)
sort.SliceStable(nums, func(i, j int) bool {
return nums[i] < nums[j]
})
outer:
for i := 0; i < len(nums)-2; i++ {
l, r := i+1, len(nums)-1
for l < r {
if nums[i]+nums[l]+nums[r] == target {
result = target
break outer
} else if nums[i]+nums[l]+nums[r] > target {
if closest > math.Abs(float64(nums[i]+nums[l]+nums[r]-target)) {
closest = math.Abs(float64(nums[i] + nums[l] + nums[r] - target))
result = nums[i] + nums[l] + nums[r]
}
r--
} else {
if closest > math.Abs(float64(nums[i]+nums[l]+nums[r]-target)) {
closest = math.Abs(float64(nums[i] + nums[l] + nums[r] - target))
result = nums[i] + nums[l] + nums[r]
}
l++
}
}
}
return result
}