[LeetCode] 719. Find K-th Smallest Pair Distance 找第K小的数对儿距离
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.
这道题给了我们一个数组,让我们找第k小的数对儿距离,数对儿距离就是任意两个数字之间的绝对值差。那么我们先来考虑最暴力的解法,是不是就是遍历任意两个数字,算出其绝对值差,然后将所有距离排序,取第k小的就行了。But,OJ 摇着头说图样图森破。但是我们可以在纯暴力搜索的基础上做些优化,从而让 OJ 说 YES。那么下面这种利用了桶排序的解法就是一种很好的优化,题目中给了数字的大小范围,不会超过一百万,所以我们就建立一百万个桶,然后还是遍历任意两个数字,将计算出的距离放到对应的桶中,这里桶不是存的具体距离,而是该距离出现的次数,桶本身的位置就是距离,所以我们才建立了一百万个桶。然后我们就可以从0开始遍历到一百万了,这样保证了我们先处理小距离,如果某个距离的出现次数大于等于k了,那么我们返回这个距离,否则就用k减去这个距离的出现次数,参见代码如下:
解法一:
class Solution {
public:
int smallestDistancePair(vector<int>& nums, int k) {
int n = nums.size(), N = ;
vector<int> cnt(N, );
for (int i = ; i < n; ++i) {
for (int j = i + ; j < n; ++j) {
++cnt[abs(nums[i] - nums[j])];
}
}
for (int i = ; i < N; ++i) {
if (cnt[i] >= k) return i;
k -= cnt[i];
}
return -;
}
};
上面的解法虽然逃脱了 OJ 的魔掌,但也仅仅是险过,并不高效。我们来看一种基于二分搜索的解法。这道题使用的二分搜索法是博主归纳总结帖 LeetCode Binary Search Summary 二分搜索法小结 中的第四种,即二分法的判定条件不是简单的大小关系,而是可以抽离出子函数的情况,下面我们来看具体怎么弄。我们的目标是快速定位出第k小的距离,那么很适合用二分法来快速的缩小查找范围,然而最大的难点就是如何找到判定依据来折半查找,即如果确定搜索目标是在左半边还是右半边。做过 Kth Smallest Element in a Sorted Matrix 和 Kth Smallest Number in Multiplication Table 这两道题的同学应该对这种搜索方式并不陌生。核心思想是二分确定一个中间数,然后找到所有小于等于这个中间数的距离个数,用其跟k比较来确定折半的方向。具体的操作是,我们首先要给数组排序,二分搜索的起始 left 为0,结束位置 right 为最大距离,即排序后的数字最后一个元素减去首元素。然后进入 while 循环,算出中间值 mid,此外我们还需要两个变量 cnt 和 start,其中 cnt 是记录小于等于 mid 的距离个数,start 是较小数字的位置,均初始化为0,然后我们遍历整个数组,先进行 while 循环,如果 start 未越界,并且当前数字减去 start 指向的数组之差大于 mid,说明此时距离太大了,我们增加减数大小,通过将 start 右移一个,那么 while 循环退出后,就有 i - start 个距离小于等于 mid,将其加入 cnt 中,举个栗子来说:
1 2 3 3 5
start i
mid = 2
如果 start 在位置0,i在位置3,那么以 nums[i] 为较大数可以产生三个(i - start)小于等于 mid 的距离,[1 3], [2 3], [3 3],这样当i遍历完所有的数字后,所有小于等于 mid 的距离的个数就求出来了,即 cnt。然后我们跟k比较,如果其小于k,那么 left 赋值为 mid+1,反之,则 right 赋值为 mid。最终返回 right 或 left 均可,参见代码如下:
解法二:
class Solution {
public:
int smallestDistancePair(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int n = nums.size(), left = , right = nums.back() - nums[];
while (left < right) {
int mid = left + (right - left) / , cnt = , start = ;
for (int i = ; i < n; ++i) {
while (start < n && nums[i] - nums[start] > mid) ++start;
cnt += i - start;
}
if (cnt < k) left = mid + ;
else right = mid;
}
return right;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/719
类似题目:
Find K Pairs with Smallest Sums
Kth Smallest Element in a Sorted Matrix
Kth Smallest Number in Multiplication Table
参考资料:
https://leetcode.com/problems/find-k-th-smallest-pair-distance/solution/
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] 719. Find K-th Smallest Pair Distance 找第K小的数对儿距离的更多相关文章
- [LeetCode] Find K-th Smallest Pair Distance 找第K小的数对儿距离
Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pai ...
- 719. Find K-th Smallest Pair Distance
Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pai ...
- 【leetcode】719. Find K-th Smallest Pair Distance
题目如下: 解题思路:对于这一类知道上限和下限,求第N位是什么的题目,可以先看看二分查找的方法可不可行.首先对nums进行排序,很显然任意两个元素距离绝对值最小是0,最大是nums[-1] - num ...
- [Swift]LeetCode719. 找出第 k 小的距离对 | Find K-th Smallest Pair Distance
Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pai ...
- 第 k 小的数
一.寻找两个有序数组的中位数 1.1 问题描述 给定两个大小为 m 和 n 的不同时为空的有序数组 nums1 和 nums2.找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m ...
- [LeetCode] K-diff Pairs in an Array 数组中差为K的数对
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in t ...
- [Swift]LeetCode668. 乘法表中第k小的数 | Kth Smallest Number in Multiplication Table
Nearly every one have used the Multiplication Table. But could you find out the k-th smallest number ...
- LeetCode 363:Max Sum of Rectangle No Larger Than K
题目链接 链接:https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/description/ 题解&代码 1 ...
- 719. 找出第 K 小的数对距离
719. 找出第 K 小的数对距离 这道题其实有那么一点二分猜答案的意思,也有很多类似题目,只不过这道题确实表达的不是很清晰不容易想到,题没问题,我的问题.既然是猜答案,那么二分边界自然就是距离最大值 ...
随机推荐
- 快速入门:Python简单实例100个(入门完整版)
Python3 100例 文章目录 Python3 100例 实例001:数字组合 实例002:“个税计算” 实例003:完全平方数 实例004:这天第几天 实例005:三数排序 实例006:斐波那契 ...
- 常见的几种 Normalization 算法
神经网络中有各种归一化算法:Batch Normalization (BN).Layer Normalization (LN).Instance Normalization (IN).Group No ...
- mybatis批量更新出现he error occurred while setting parameters
当你更新一条时,不会发生问题,但是执行多条就出现了错误原因是mysql 配置jdbc:driver 应该添加&allowMultiQueries=trueurl:jdbc:mysql://lo ...
- sentry 9.1.1docker版onepremise过程记录
sentry安装:https://github.com/getsentry/onpremise正确使用此文档安装步骤,安装版本9.1.1-onbuild,这个需要自改Dockerfile. 备注:构建 ...
- Knative 初体验:CICD 极速入门
Knative 社区很早就在讨论用 Tekton 替换 Build 模块的相关事宜.Knative Build 官方已经正式说明不再建议使用 Knative Build 了. 如果你知道 Knativ ...
- 微信小程序小Demo
微信小程序小Demo 调用API,轮播图,排行榜,底部BabTar的使用... board // board/board.js Page({ /** * 页面的初始数据 */ // 可以是网络路径图片 ...
- 如何当上Leader和六千个bug的系统
在昨天的读书会上我分享了我是如何当上leader以及当上leader之后的体会.然后今天Sophie总结了我的发言,大家对此有些反馈.我根据大家的反馈写了这篇文章,主要针对几点: 大家如何当上lead ...
- Elastic Stack核心产品介绍-Elasticsearch、Logstash和Kibana
Elastic Stack 是一系列开源产品的合集,包括 Elasticsearch.Kibana.Logstash 以及 Beats 等等,能够安全可靠地获取任何来源.任何格式的数据,并且能够实时地 ...
- Markdown 基础学习
Markdown是什么? Markdwon是一种轻量级标记语言,它以纯文本形式(易读.易写.易更改)编写文档,并最终以HTLM格式发布.Markdown也可以理解为将以 MARKDOWN语法编写 ...
- Java自学-I/O 对象流
Java 对象流 ObjectInputStream,ObjectOutputStream 对象流指的是可以直接把一个对象以流的形式传输给其他的介质,比如硬盘 一个对象以流的形式进行传输,叫做序列化. ...