[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循环依赖
a.py from b import b print '---------this is module a.py----------' def a(): print "hello, a&qu ...
- LeetCode 141:环形链表 Linked List Cycle
给定一个链表,判断链表中是否有环. 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始). 如果 pos 是 -1,则在该链表中没有环. Given a l ...
- linux 链接mysql并覆盖数据
--链接mysql 命令格式: mysql -h 主机地址 -u 用户名 -p --按回车输入密码 --在服务器里登录到数据库里 ,使用某个库,gtmc 代表数据库名称 use gtmc --覆盖数据 ...
- Kubernetes 之 Nameserver limits were exceeded
1.问题描述 最近查看kubernetes 的events,发现了有两个节点经常出现下面的信息: DNSConfigForming Nameserver limits were exceeded, s ...
- Spring Cloud Eureka 服务注册中心(二)
序言 Eureka 是 Netflix 开发的,一个基于 REST 服务的,服务注册与发现的组件 它主要包括两个组件:Eureka Server 和 Eureka Client Eureka Clie ...
- Logstash:运用jdbc_streaming来丰富我们的数据
需要学习的地方:使用logstash获取数据后,然后根据这些数据再从MySQL数据库中进行匹配,增加一些数据到logstash的数据流中,然后输出到es 在IoT物联网时代,我们经常会遇到从传感器采集 ...
- 通过Filebeat把日志传入到Elasticsearch
学习的地方:配置文件中预先处理字段数据的用法 通过Filebeat把日志传入到Elasticsearch Elastic Stack被称之为ELK (Elasticsearch,Logstash an ...
- 绑定 Binding Path=.,Binding.,Binding Source={StaticResource ResourceKey="Hello"} xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:sys="clr-namespace:System;assembly=mscorlib" <Window.Resources> <Style Targ ...
- 用ASP.NET创建数据库
小白的第一次使用: 程序员写程序,就好比一个物品的慢慢诞生,我们今天的这个例子就可以想象成一个物品慢慢的在编译的过程中,让我们所看到 一.创建我们所测试的项目 1.创建一个简单的带有模型层(Model ...
- python——Tkinter图形化界面及threading多线程
Tkinter模块("Tk 接口")是Python的标准Tk GUI工具包的接口.Tk和Tkinter可以在大多数的Unix平台下使用,同样可以应用在Windows和Macinto ...