Thanks to visit codestin.com
Credit goes to github.com

Skip to content

create 0016-3sum-closest.go #2208

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}