go: add «719. Find K-th Smallest Pair Distance»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-14 21:39:14 +02:00
parent cd8500e6bc
commit 9b4f9e0847
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,37 @@
package main
import "slices"
func smallestDistancePair(nums []int, k int) int {
pairsWithMaxDistance := func(distance int) int {
count := 0
left := 0
for right := 0; right < len(nums); right++ {
for nums[right]-nums[left] > distance {
left++
}
count += right - left
}
return count
}
slices.Sort(nums)
low, high := 0, nums[len(nums)-1]-nums[0]
for low < high {
mid := (low + high) / 2
count := pairsWithMaxDistance(mid)
if count < k {
low = mid + 1
} else {
high = mid
}
}
return low
}