go: add «719. Find K-th Smallest Pair Distance»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
cd8500e6bc
commit
9b4f9e0847
1 changed files with 37 additions and 0 deletions
37
go/find-k-th-smallest-pair-distance.go
Normal file
37
go/find-k-th-smallest-pair-distance.go
Normal 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
|
||||
}
|
Loading…
Reference in a new issue