From 9b8f7c610fe02b3f0a5f32853eb4c75060b31c8f Mon Sep 17 00:00:00 2001 From: Youssef Eddaif Date: Sat, 4 Feb 2023 11:39:28 +0100 Subject: [PATCH] create 0016-3sum-closest.go --- go/0016-3sum-closest.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 go/0016-3sum-closest.go 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