Skip to content

Commit ccff5cd

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

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,22 +101,22 @@ 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) {
113+
while (right < nums.length && count < k) {
114114
int left = 0;
115-
while (nums[right] - nums[left] > d) left++;
115+
while (nums[right] - nums[left] > d && left < right) left++;
116116
count += right - left;
117117
right++;
118118
}
119-
return count;
119+
return count < k;
120120
}
121121
}
122122
```

0 commit comments

Comments
 (0)