Skip to content

Commit 173d76e

Browse files
authored
Merge pull request neetcode-gh#2208 from unrealjo/main
create 0016-3sum-closest.go
2 parents 08d96b9 + 9b8f7c6 commit 173d76e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

go/0016-3sum-closest.go

Lines changed: 36 additions & 0 deletions
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy