05 August 2008
一对整数 a 和 b 的距离定义为 a 和 b 之间的绝对差。
给定一个整数数组 nums 和一个整数 k,返回所有对 nums[i] 和 nums[j] 中第 k 个最小的距离,其中 0 <= i < j < nums.length。
两个二分搜索
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums);
int lo = 0, hi = nums[nums.length - 1] - nums[0];
while(lo < hi){ //Find the smallest workable number, i.e. find the first T in a ...FFFFTTTT... sequence
int mid = lo + (hi - lo) / 2;
if (cover(nums, mid, k)) hi = mid; //is the number we guess enough to cover k?
else lo = mid + 1;
}
return lo;
}
//Return true if we have enough number to cover k, false otherwise.
private boolean cover(int[] nums, int guess, int k){
int cnt = 0, n = nums.length;
for (int i = 0; i < n && cnt < k; i++){
int lo = i, hi = n - 1;
while(lo < hi){
int mid = lo + (hi - lo + 1) / 2;
if (nums[mid] <= nums[i] + guess) lo = mid;
else hi = mid - 1;
}
cnt += lo - i;
}
return cnt >= k;
}
}
Sliding Window
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums);
int lo = 0, hi = nums[nums.length - 1] - nums[0];
while(lo < hi){//Find the smallest workable number, i.e. find the first T in a ...FFFFTTTT... sequence
int mid = lo + (hi - lo) / 2;
if (cover(nums, mid, k)) hi = mid; //is the number we guess enough to cover k?
else lo = mid + 1;
}
return lo;
}
//Return true if we have enough number to cover k, false otherwise.
private boolean cover(int[] nums, int guess, int k){
int cnt = 0;
for (int i = 0, j = 0; i < nums.length && cnt < k; i++){ //j = left end, i = right end
while(nums[i] - nums[j] > guess) j++;
cnt += i - j; //For every pair that ends at i, there are (j, i), (j + 1, i), ..., (i - 1, i) = i - j pairs
}
return cnt >= k;
}
}