Skip to content

Commit

Permalink
create 0016-3sum-closest.go
Browse files Browse the repository at this point in the history
  • Loading branch information
Youssef Eddaif committed Feb 4, 2023
1 parent 9154cf7 commit 9b8f7c6
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions go/0016-3sum-closest.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 9b8f7c6

Please sign in to comment.