Skip to content

Commit b2cd9fd

Browse files
committed
719
1 parent de5f346 commit b2cd9fd

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

algorithms/p719/719.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package p719
2+
3+
import (
4+
"sort"
5+
)
6+
7+
func countDistance(nums []int, d int) int {
8+
//slide window
9+
l, r := 0, 0
10+
cnt := 0
11+
for r < len(nums) {
12+
for r < len(nums) && nums[r]-nums[l] <= d {
13+
cnt += r - l
14+
r++
15+
}
16+
if r < len(nums) {
17+
for nums[r]-nums[l] > d {
18+
l++
19+
}
20+
}
21+
}
22+
return cnt
23+
}
24+
25+
func smallestDistancePair(nums []int, k int) int {
26+
sort.Ints(nums)
27+
if len(nums) <= 1 {
28+
return 0
29+
}
30+
n := nums[len(nums)-1] - nums[0]
31+
v := sort.Search(n, func(i int) bool {
32+
return countDistance(nums, i) >= k
33+
})
34+
return v
35+
}

algorithms/p719/719_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package p719
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func Test0(t *testing.T) {
10+
11+
nums := []int{1, 3, 1}
12+
assert.Equal(t, 0, smallestDistancePair(nums, 1))
13+
}
14+
15+
func TestCount(t *testing.T) {
16+
nums := []int{1, 2, 3, 4, 5}
17+
assert.Equal(t, 7, countDistance(nums, 2))
18+
}

0 commit comments

Comments
 (0)