diff --git a/leetcode/binary-search/719-find-k-th-smallest-pair-distance.md b/leetcode/binary-search/719-find-k-th-smallest-pair-distance.md index 07ceb33..666dd43 100644 --- a/leetcode/binary-search/719-find-k-th-smallest-pair-distance.md +++ b/leetcode/binary-search/719-find-k-th-smallest-pair-distance.md @@ -101,22 +101,25 @@ class Solution { int lo = 0, hi = nums[nums.length - 1] - nums[0]; while (lo != hi) { int mi = lo + (hi - lo) / 2; - if (count(nums, mi) < k) lo = mi + 1; + if (isCountBelowThreshold(nums, mi, k)) lo = mi + 1; else hi = mi; } return lo; } - private int count(int[] nums, int d) { + private boolean isCountBelowThreshold(int[] nums, int d, int k) { int right = 1; int count = 0; - while (right < nums.length) { - int left = 0; - while (nums[right] - nums[left] > d) left++; - count += right - left; - right++; + int left = 0; + while (right < nums.length && count < k) { + if (nums[right] - nums[left] > d) { + ++left; + } else { + count += right - left; + ++right; + } } - return count; + return count < k; } } ```