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:

  1. 2 <= len(nums) <= 10000.
  2. 0 <= nums[i] < 1000000.
  3. 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

Find K Closest Elements

Kth Smallest Number in Multiplication Table

K-th Smallest Prime Fraction

参考资料:

https://leetcode.com/problems/find-k-th-smallest-pair-distance/solution/

https://leetcode.com/problems/find-k-th-smallest-pair-distance/discuss/109077/C++-counting-sort-O(n2)-and-binary-search-O(nlogn)

https://leetcode.com/problems/find-k-th-smallest-pair-distance/discuss/109082/Approach-the-problem-using-the-%22trial-and-error%22-algorithm

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 719. Find K-th Smallest Pair Distance 找第K小的数对儿距离的更多相关文章

  1. [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 ...

  2. 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 ...

  3. 【leetcode】719. Find K-th Smallest Pair Distance

    题目如下: 解题思路:对于这一类知道上限和下限,求第N位是什么的题目,可以先看看二分查找的方法可不可行.首先对nums进行排序,很显然任意两个元素距离绝对值最小是0,最大是nums[-1] - num ...

  4. [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 ...

  5. 第 k 小的数

    一.寻找两个有序数组的中位数 1.1 问题描述 给定两个大小为 m 和 n 的不同时为空的有序数组 nums1 和 nums2.找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m ...

  6. [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 ...

  7. [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 ...

  8. LeetCode 363:Max Sum of Rectangle No Larger Than K

    题目链接 链接:https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/description/ 题解&代码 1 ...

  9. 719. 找出第 K 小的数对距离

    719. 找出第 K 小的数对距离 这道题其实有那么一点二分猜答案的意思,也有很多类似题目,只不过这道题确实表达的不是很清晰不容易想到,题没问题,我的问题.既然是猜答案,那么二分边界自然就是距离最大值 ...

随机推荐

  1. jQuery 源码分析(二) 入口模块

    jQuery返回的对象本质上是一个JavaScript对象,而入口模块则可以保存对应的节点的引用,然后供其它模块操作 我们创建jQuery对象时可以给jQuery传递各种不同的选择器,如下: fals ...

  2. 在 .NET Core 中使用异步的 ADO.NET 的简单示例

    直接贴代码: Program.cs using Microsoft.Extensions.Configuration; using System; using System.Data; using S ...

  3. 『月之谜 数位dp』

    月之谜 Description 打败了Lord lsp 之后,由 于lqr 是一个心地善良的女孩 子,她想净化Lord lsp 黑化的 心,使他变回到原来那个天然 呆的lsp--在倒霉的光之英 雄ap ...

  4. 第三章 web设计原则:

    程序员的修炼从优秀带卓越 第三章 web设计原则:    网站的评判标准     加载的速度要快     这到底是什么东西     给我看一个例子     清清楚楚的告诉我要做什么,并且扫除障碍   ...

  5. springboot拦截器拦了静态资源css,js,png,jpeg,svg等等静态资源

    1.在SpringBoot中自己写的拦截器,居然把静态资源也拦截了,导致了页面加载失败. package com.bie.config; import com.bie.component.MyLoca ...

  6. ASP.NET Core快速入门(第1章:介绍与引入)--学习笔记

    课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 任务1:课程介绍 1.介绍与引入 2.配置管理 3.依赖注入 4.ASP.NE ...

  7. WPF DataGrid row background converter datagrid 行背景随绑定数据变化,转换器

    <DataGrid Grid.Row=" ItemsSource="{Binding SalesList,UpdateSourceTrigger=PropertyChange ...

  8. ConsoleColor原来有16种, enumData.GetValue(i)

    Console.WriteLine("Name:{0},Value:{0:D}", enumData.GetValue(i)); Name:Black,Value:0Name:Da ...

  9. Server2016 IIS安装配置

  10. sql基础语句50条

    curdate() 获取当前日期 年月日 curtime() 获取当前时间 时分秒 sysdate() 获取当前日期+时间 年月日 时分秒 */ order by bonus desc limit ( ...