1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/go/find-k-th-smallest-pair-distance.go
Matej Focko 9b4f9e0847
go: add «719. Find K-th Smallest Pair Distance»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-08-14 21:39:14 +02:00

37 lines
541 B
Go

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
}