题目
Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B.
Example 1:
Input:
nums = [1,3,1]
k = 1
Output: 0
Explanation:
Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
Note:
2 <= len(nums) <= 10000.
0 <= nums[i] < 1000000.
1 <= k <= len(nums) * (len(nums) - 1) / 2.
分析
这题做题时看出二分了, 十分可惜,没想到是两次二分,回头看了第一名代码ac
现在来分析题目
看到题目时 ,我先用native 算法 n平方的试试了,超时了
接着我们容易观察到
答案的范围时[最小差,最大差]
并且 观察 答案是有递增性的
这里离目标很近了接下来是判断有多少个小于中间值
这里又来了一次二分
我们会排序数组
然后二分查找
找出 差《= mid 的数
代码
class Solution {
public:
int f(vector<int>& a, int m) {
int res = 0;
for(int i = 0; i < a.size(); i++) {
res += (upper_bound(a.begin(), a.end(), a[i] + m) - (a.begin() + i + 1));
}
return res;
}
int smallestDistancePair(vector<int>& nums, int k) {
sort( nums.begin() , nums.end() );
int left =0 ;
int right = nums.back() - nums[0];
while( left <= right ){
int mid = ( right -left ) / 2 + left ;
if( f( nums, mid ) >= k )
right = mid -1 ;
else
left = mid + 1 ;
}
return left ;
}
};
时间复杂度
O(N∗logN∗logM)
这里分析一下答案的二分用的时间复杂度是log(最大差(M))
接着是数组的O(n)*log(n)