Skip to content

Commit 9b8f7c6

Browse files
author
Youssef Eddaif
committed
create 0016-3sum-closest.go
1 parent 9154cf7 commit 9b8f7c6

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

go/0016-3sum-closest.go

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package threeSumClosest
2+
3+
import (
4+
"math"
5+
"sort"
6+
)
7+
8+
func threeSumClosest(nums []int, target int) int {
9+
Length := len(nums)
10+
// Sort given array of numbers
11+
sort.Ints(nums)
12+
var left, right, sum, diff, result int
13+
min := math.MaxInt
14+
for i := 0; i < Length-2; i++ {
15+
left = i + 1
16+
right = Length - 1
17+
for left < right {
18+
sum = nums[left] + nums[right] + nums[i]
19+
// Calculate the distance between the target and sum
20+
diff = int(math.Abs(float64(target - sum)))
21+
if sum < target {
22+
left++
23+
} else if sum > target {
24+
right--
25+
} else {
26+
return sum
27+
}
28+
// Check for smallest distance from the target
29+
if diff < min {
30+
min = diff
31+
result = sum
32+
}
33+
}
34+
}
35+
return result
36+
}

0 commit comments

Comments
 (0)