Skip to content

Commit 276afb2

Browse files
committed
feat: further improve sliding window search
Short exit when we already have the information we want
1 parent e808748 commit 276afb2

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

leetcode/binary-search/719-find-k-th-smallest-pair-distance.md

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -101,22 +101,25 @@ class Solution {
101101
int lo = 0, hi = nums[nums.length - 1] - nums[0];
102102
while (lo != hi) {
103103
int mi = lo + (hi - lo) / 2;
104-
if (count(nums, mi) < k) lo = mi + 1;
104+
if (isCountBelowThreshold(nums, mi, k)) lo = mi + 1;
105105
else hi = mi;
106106
}
107107
return lo;
108108
}
109109

110-
private int count(int[] nums, int d) {
110+
private Boolean isCountBelowThreshold(int[] nums, int d, int k) {
111111
int right = 1;
112112
int count = 0;
113-
while (right < nums.length) {
114-
int left = 0;
115-
while (nums[right] - nums[left] > d) left++;
116-
count += right - left;
117-
right++;
113+
int left = 0;
114+
while (right < nums.length && count < k) {
115+
if (nums[right] - nums[left] > d) {
116+
++left;
117+
} else {
118+
count += right - left;
119+
++right;
120+
}
118121
}
119-
return count;
122+
return count < k;
120123
}
121124
}
122125
```

0 commit comments

Comments
 (0)