38 lines
541 B
Go
38 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
|
||
|
}
|