diff --git a/go/0016-3sum-closest.go b/go/0016-3sum-closest.go new file mode 100644 index 000000000..e704bd02e --- /dev/null +++ b/go/0016-3sum-closest.go @@ -0,0 +1,36 @@ +package threeSumClosest + +import ( + "math" + "sort" +) + +func threeSumClosest(nums []int, target int) int { + Length := len(nums) + // Sort given array of numbers + sort.Ints(nums) + var left, right, sum, diff, result int + min := math.MaxInt + for i := 0; i < Length-2; i++ { + left = i + 1 + right = Length - 1 + for left < right { + sum = nums[left] + nums[right] + nums[i] + // Calculate the distance between the target and sum + diff = int(math.Abs(float64(target - sum))) + if sum < target { + left++ + } else if sum > target { + right-- + } else { + return sum + } + // Check for smallest distance from the target + if diff < min { + min = diff + result = sum + } + } + } + return result +} 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