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 consider the fraction p/q.
What is the K-th smallest fraction considered? Return your answer as an array of ints, where answer[0] = p and 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:
Awill have length between2and2000.- Each
A[i]will be between1and30000. Kwill be between1andA.length * (A.length - 1) / 2.
Approach #1: brute force.[Time Limit Exceeded]
class Solution {
public:
vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) {
int n = A.size();
vector<pair<int, int>> temp;
vector<int> ans;
for (int i = 0; i < n; ++i) {
for (int j = i+1; j < n; ++j) {
temp.push_back({A[i], A[j]});
}
}
sort(temp.begin(), temp.end(), cmp);
ans.push_back(temp[K-1].first);
ans.push_back(temp[K-1].second);
return ans;
}
static bool cmp (pair<int, int> a, pair<int, int> b) {
return (double)a.first/a.second < (double)b.first/b.second;
}
};
Approach #2: Binary Search.
class Solution {
public:
vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) {
int n = A.size();
double l = 0.0, r = 1.0;
while (l < r) {
double m = (l + r) / 2;
double max_f = 0.0;
int total = 0;
int p, q;
int j = 1;
for (int i = 0; i < n-1; ++i) {
while (j < n && A[i] > m * A[j]) ++j;
total += (n - j);
if (j == n) break;
double f = static_cast<double>(A[i]) / A[j];
if (f > max_f) {
p = i;
q = j;
max_f = f;
}
}
if (total == K) return {A[p], A[q]};
else if (total < K) l = m;
else r = m;
}
return {};
}
};
Runtime: 12 ms, faster than 83.88% of C++ online submissions for K-th Smallest Prime Fraction.
Analysis:
1. why use static_cast<>?
In short:
static_cast<>()gives you a compile time checking ability, C-Style cast doesn't.static_cast<>()can be spotted easily anywhere inside a C++ source code; in contrast, C_Style cast is harder to spot.- Intentions are conveyed much better using C++ casts.
More Explanation:
The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.
char c = 10; // 1 byte
int *p = (int*)&c; // 4 bytesSince this results in a 4-byte pointer pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.
*p = 5; // run-time error: stack corruptionIn contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.
int *q = static_cast<int*>(&c); // compile-time error
2. In this way we make m as a flag (range is from 0 to 1), we can count the numbers which elements less than m. when if m == K we return {A[p], A[q]} , else if m > K => r = m; else l = m
we can use a matrix to instore the A[i] / A[j], but in order to reduce the time complexity we can use under code to realize.
for (int i = 0; i < n-1; ++i)
while (j < n && A[i] > m * A[j]) ++j;
for every loop j can be using repeatedly, because when i increase, in order to make A[i] > m * A[j], j must bigger than last loop.
786. K-th Smallest Prime Fraction的更多相关文章
- [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 ...
- [LeetCode] 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 ...
- [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 ...
- 【LeetCode】堆 heap(共31题)
链接:https://leetcode.com/tag/heap/ [23] Merge k Sorted Lists [215] Kth Largest Element in an Array (无 ...
- 【LeetCode】二分 binary_search(共58题)
[4]Median of Two Sorted Arrays [29]Divide Two Integers [33]Search in Rotated Sorted Array [34]Find F ...
- [LeetCode] 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 ...
- [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 ...
- [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 pai ...
- [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 ...
随机推荐
- 转: 性能测试应该怎么做? (from coolshell.cn)
转自: http://coolshell.cn/articles/17381.html 偶然间看到了阿里中间件Dubbo的性能测试报告,我觉得这份性能测试报告让人觉得做这性能测试的人根本不懂性能测试, ...
- Odoo HR Payslip
pay slip 可以录入多条 worked_days_line 和 input_line,用来人工调整薪资变动部分,比如销售提成,扣款等. pay slip 可以包含多个pay slip line ...
- 协议的注冊与维护——ndpi源代码分析
在前面的文章中,我们对ndpi中的example做了源代码分析.这一次我们将尽可能深入的了解ndpi内部的结构和运作.我们将带着以下三个目的(问题)去阅读ndpi的源代码. 1.ndpi内部是怎么样注 ...
- 使用maven创建项目和cannot change version web module 3.0
近期下载了最新的Eclipse mars.2, 这个eclipse自带了maven插件,于是就用maven尝试创建一个java web项目. 第一步,例如以下图所看到的选择 Maven Project ...
- Linux变量内容的删除、代替与替换
变量内容的删除与代替 范例一:先让小写的 path 自己定义变量配置的与 PATH 内容同样 [root@www ~]# path=${PATH} [root@www ~]# echo $path / ...
- AOP是怎么实现的,有几种方式
1.静态AOP:在编译期,切面直接以字节 码的形式编译到目标字节 码文件中. AspectJ属于静态AOP,是在编译时进行增强,会在编译的时候将AOP逻辑织入到代码中,需要专有的编译器和织入器. 优点 ...
- 项目Alpha冲刺(团队10/10)
项目Alpha冲刺(团队10/10) 团队名称: 云打印 作业要求: 项目Alpha冲刺(团队) 作业目标: 完成项目Alpha版本 团队队员 队员学号 队员姓名 个人博客地址 备注 22160041 ...
- Android Baseline小tip
转载请注明出处:http://blog.csdn.net/bbld_/article/details/40709353 Baseline Alignment
- cocos2dx学习进度
将cocos2dx实战上面的例子都自己过一遍,手动敲一边里面的代码,瓦片地图,地图滚动,碰撞,容器类,现在搞到了fileUtils相关的了,哦,官方叫做数据持久化,一不小心就6点了,时间过得太快了,看 ...
- 组合式+迭代式+链式 MapReduce
1.迭代式mapreduce 一些复杂的任务难以用一次mapreduce处理完成,需要多次mapreduce才能完成任务,例如Pagrank,Kmeans算法都需要多次的迭代,关于mapreduce迭 ...