A sorted list A contains 1, plus some number of primes.  Then, for every p < q in the list, we consider the fraction p/q.

What is the K-th smallest fraction considered?  Return your answer as an array of ints, where answer[0] = pand answer[1] = q.

Examples:
Input: A = [1, 2, 3, 5], K = 3
Output: [2, 5]
Explanation:
The fractions to be considered in sorted order are:
1/5, 1/3, 2/5, 1/2, 3/5, 2/3.
The third fraction is 2/5. Input: A = [1, 7], K = 1
Output: [1, 7]

Note:

  • A will have length between 2 and 2000.
  • Each A[i] will be between 1 and 30000.
  • K will be between 1 and A.length * (A.length - 1) / 2.

这道题给了我们一个有序数组,里面是1和一些质数,说是对于任意两个数,都可以组成一个 [0, 1] 之间分数,让求第K小的分数是什么,题目中给的例子也很好的说明了题意。那么最直接暴力的解法就是遍历出所有的分数,然后再进行排序,返回第K小的即可。但是这种无脑暴力搜索的方法 OJ 是不答应的,无奈,只能想其他的解法。由于数组是有序的,所以最小的分数肯定是由第一个数字和最后一个数字组成的,而接下来第二小的分数就不确定是由第二个数字和最后一个数字组成的,还是由第一个数字跟倒数第二个数字组成的。这里用一个最小堆来存分数,那么每次取的时候就可以将最小的分数取出来,由于前面说了,不能遍历所有的分数都存入最小堆,那么该怎么办呢,可以先存n个,哪n个呢?其实就是数组中的每个数字都和最后一个数字组成的分数。由于需要取出第K小的分数,那么在最小堆中取K个分数就可以了,第一个取出的分数就是那个由第一个数字和最后一个数字组成的最小的分数,然后就是精髓所在了,此时将分母所在的位置前移一位,还是和当前的分子组成新的分数,这里即为第一个数字和倒数第二个数字组成的分数,存入最小堆中,那么由于之前已经将第二个数字和倒数第一个数字组成的分数存入了最小堆,所以不用担心第二小的分数不在堆中,这样每取出一个分数,都新加一个稍稍比取出的大一点的分数,这样取出了第K个分数即为所求,参见代码如下:

解法一:

class Solution {
public:
vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) {
priority_queue<pair<double, pair<int, int>>> q;
for (int i = ; i < A.size(); ++i) {
q.push({-1.0 * A[i] / A.back(), {i, A.size() - }});
}
while (--K) {
auto t = q.top().second; q.pop();
--t.second;
q.push({-1.0 * A[t.first] / A[t.second], {t.first, t.second}});
}
return {A[q.top().second.first], A[q.top().second.second]};
}
};

其实这道题比较经典的解法是用二分搜索法 Binary Search,使用的二分搜索法是博主归纳总结帖 LeetCode Binary Search Summary 二分搜索法小结 中的第四种,即二分法的判定条件不是简单的大小关系,而是可以抽离出子函数的情况,下面来看具体怎么弄。这种高级的二分搜索法在求第K小的数的时候经常使用,比如 Kth Smallest Element in a Sorted MatrixKth Smallest Number in Multiplication Table,和 Find K-th Smallest Pair Distance 等。思路都是用 mid 当作 candidate,然后统计小于 mid 的个数 cnt,和K进行比较,从而确定折半的方向。这道题也是如此,mid 为候选的分数值,刚开始时是 0.5,然后需要统计出不大于 mid 的分数都个数 cnt,同时也需要找出最接近 mid 的分数,当作返回的候选值,因为一旦 cnt 等于K了,直接将这个候选值返回即可,这个候选值分数是由p和q来表示的,其中p表示分子,初始化为0,q表示分母,初始化为1(因为除数不能为0),在内部的 while 循环退出时,分数 A[i]/A[j] 就是最接近 mid 的候选者,此时假如 p/q 要小于 A[i]/A[j],就要分别更新p和q。否则如果 cnt 小于K,说明应该增大一些 mid,将 left 赋值为 mid,反之如果 cnt 大于K,需要减小 mid,将 right 赋值为 mid,参见代码如下:

解法二:

class Solution {
public:
vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) {
double left = , right = ;
int p = , q = , cnt = , n = A.size();
while (true) {
double mid = left + (right - left) / 2.0;
cnt = ; p = ;
for (int i = , j = ; i < n; ++i) {
while (j < n && A[i] > mid * A[j]) ++j;
cnt += n - j;
if (j < n && p * A[j] < q * A[i]) {
p = A[i];
q = A[j];
}
}
if (cnt == K) return {p, q};
if (cnt < K) left = mid;
else right = mid;
}
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/786

类似题目:

Find K Pairs with Smallest Sums

Kth Smallest Element in a Sorted Matrix

Kth Smallest Number in Multiplication Table

Find K-th Smallest Pair Distance

参考资料:

https://leetcode.com/problems/k-th-smallest-prime-fraction/

https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/115531/C++-9lines-priority-queue

https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/115819/Summary-of-solutions-for-problems-%22reducible%22-to-LeetCode-378

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

[LeetCode] K-th Smallest Prime Fraction 第K小的质分数的更多相关文章

  1. [LeetCode] 786. K-th Smallest Prime Fraction 第K小的质分数

    A sorted list A contains 1, plus some number of primes.  Then, for every p < q in the list, we co ...

  2. 786. K-th Smallest Prime Fraction

    A sorted list A contains 1, plus some number of primes.  Then, for every p < q in the list, we co ...

  3. [Swift]LeetCode786. 第 K 个最小的素数分数 | K-th Smallest Prime Fraction

    A sorted list A contains 1, plus some number of primes.  Then, for every p < q in the list, we co ...

  4. 【LeetCode】1022. Smallest Integer Divisible by K 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  5. 【leetcode】1022. Smallest Integer Divisible by K

    题目如下: Given a positive integer K, you need find the smallest positive integer N such that N is divis ...

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

  7. [LeetCode] 378. Kth Smallest Element in a Sorted Matrix 有序矩阵中第K小的元素

    Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth ...

  8. [leetcode] 230. Kth Smallest Element in a BST 找出二叉搜索树中的第k小的元素

    题目大意 https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/ 230. Kth Smallest Elem ...

  9. [LeetCode] 230. Kth Smallest Element in a BST 二叉搜索树中的第K小的元素

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

随机推荐

  1. Angular记录(1)

    文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...

  2. DTO/DO等POJO对象的使用场景和 orika-mapper 框架的使用

    对于项目而言, 我们一般会有DAO->Service->Controller分层设计, 这些层次体现了每层的作用, 而层次之间的数据传递对象设计很少被提及, 下面是一个相对完整的数据转换过 ...

  3. [再寄小读者之数学篇](2014-05-27 矩阵的迹与 Jacobian)

    (from MathFlow) 设 $A=(a_{ij})$, 且定义 $$\bex \n_A f(A)=\sex{\cfrac{\p f}{\p a_{ij}}}. \eex$$ 试证: (1) $ ...

  4. Pipeline build step with parameters

    build step https://jenkins.io/doc/pipeline/steps/pipeline-build-step/#build-build-a-job 一个任务的执行触发,另外 ...

  5. UIWebView代码注入时机与姿势

    一个奇怪的业务场景,引发的胡乱思考 问题其实不难解决,只是顺着这个问题,发散出了一些有意思的东西 本文旨在讨论UIWebView,WKWebView有自己的机制,不用这么费劲 我们的业务最大的最重要的 ...

  6. 使用node.js 脚手架搭建Vue项目

    1.安装node.js https://nodejs.org/zh-cn/ 下载安装node.js 在命令行测试 node -v 输出版本号说明安装成功 2.使用npm更新安装cpnm npm ins ...

  7. C语言之路-3-循环

    1.while循环计算数字位数 #include<stdio.h> int main() { ; int x; printf("请输入数字:"); scanf(&quo ...

  8. python进制转化函数,10进制字符串互转,16进制字符串互转

    来了老弟,emmmmm,今天想到平时经常用到编码转化,把字符串转化为16进制绕过等等的,今天想着用python写个玩,查询了一些资料,看了些bolg 上面的两个函数是将二进制流转化为16进制,data ...

  9. mybatis基础知识

    一.什么是Mybatis 这里借用官网的一句话介绍什么是mybatis:MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC ...

  10. 【原创】大数据基础之ElasticSearch(4)es数据导入过程

    1 准备analyzer 内置analyzer 参考:https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis- ...