您的位置:首页 > 大数据 > 人工智能

LeetCode719. Find K-th Smallest Pair Distance (hard)

2018-03-09 17:46 323 查看
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:
class
dfaf
2 <= len(nums) <= 10000
.
0 <= nums[i] < 1000000
.
1 <= k <= len(nums) * (len(nums) - 1) / 2
.
这道题暴力破解的思想非常简单,但是会超时,所以找到其他的解决方法,这道题我想了很久,但是没有想到方法,只好去看Solution首先对数组进行排序,然后选择距离的最大边界和最小边界,最小边界设置为0,最大边界就是排序后的数组的最后一个元素减去数组的第一个元素。知道了最大距离和最小距离,这里采用二分查找类似的思想,但是对其进行稍微的改动,假设最大距离和最小距离的中间值为m,然后定义一个count来计数,用来存储小于m的个数,如果这个个数大于目标k,那么我们就通过减小m来继续进行比较,如果小于m,那就增大m,这里都采用二分查找的思想。然后找到大于m的距离的个数是另一个不容易想到的点,或者说稍微有点难度的点,我们设置一个左边的索引和一个右边的索引left 和right,先让右边不动,如果距离大于m,则让left向右移动,用while控制这个判断,然后知道跳出来,跳出来之后,统计right到从left到right的的个数,比如,right到left,right到left+1....所以个数是right-left。这里比Solution里面多了一个判断,这样判断可以减少多余的判断次数,如果count>k直接跳出,因为没有必要继续统计下去,因为减小m的值。
然后直接返回l,因为跳出了l<h的循环,所以所求即使l。
class Solution {
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums);
int l = 0;
int h = nums[nums.length-1]-nums[0];
while(l<h){
int m = (h+l)/2;
int left = 0,count = 0;
for(int right = 0;right<nums.length;++right){
while(nums[right]-nums[left]>m) left++;
count +=right - left;
if(count>k) break;
}
if(count>=k) h = m;
else l = m + 1;
}
return l;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: