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 ...
随机推荐
- UP Board USB无线网卡选购指南
前言 原创文章,转载引用务必注明链接,水平有限,欢迎指正. 本文环境:ubilinux 3.0 kernel 4.4.0 本文使用Markdown写成,为获得更好的阅读体验和正常的图片.链接,请访问我 ...
- Linux内存管理之mmap详解 (可用于android底层内存调试)
注:将android底层malloc换为mmap来获取内存,可将获取到的内存添加tag,从而再利用meminfo进行分析,可单独查看该tag的内存,从而进行分析. 一. mmap系统调用 1. mma ...
- 【转载】Http协议与TCP协议简单理解后续
写了这么长时间的代码,发现自己对TCP/IP了解的并不是很透彻.虽然会用C#的HttpClient类来进行网络编程,也可以使用Chrome的开发者工具来检测每一次的HTTP请求的报文头与报文体,也知道 ...
- (转)C系程序员面试必知必会之大端小端
C程序员经常被问及的一道面试题是:什么是大端/小端,怎么样判断是大端/小端?大端小端问题对于嵌入式程序员绝对不会陌生(否则,别告诉我你是搞嵌入式的),它与CPU体系结构有关.比如常见的X86处理器 ...
- Centos6.5 安装 Oracle11gR2(64位)
Centos6.5安装 Oracle11gR2(64位) 安装centos6.5 (我的是虚拟机环境) 1. 下载centos6.5的安装包,不解释. 例如以下图: 2. 下载oracle安装包, ...
- c++学习笔记之基础---类内声明函数后在类外定义的一种方法
在C++的“类”中经常遇到这样的函数, 返回值类型名 类名::函数成员名(参数表){ 函数体.} 双冒号的作用 ::域名解析符!返回值类型名 类名::函数成员名(参数表) { 函数体. } 这个是在类 ...
- bash shell最基本的语法
1 shell语句的基本构成 shell每个基本的构成元素之间都相隔一个空格. 比如[ -e file ],[.-e.file.]这四个基本元素之间都相隔了一个空格. 同样的道理[ ! -e file ...
- svgo
SVG精简压缩工具svgo简介和初体验 SVG精简压缩工具svgo简介和初体验 « 张鑫旭-鑫空间-鑫生活 https://www.zhangxinxu.com/wordpress/2016/02/s ...
- hdfs namenode出错
http://hadoop.apache.org/docs/r1.0.4/cn/hdfs_design.html 健壮性 HDFS的主要目标就是即使在出错的情况下也要保证数据存储的可靠性.常见的三种出 ...
- Fibonacci数列(找规律)
题目描述 Fibonacci数列是这样定义的:F[0] = 0F[1] = 1for each i ≥ 2: F[i] = F[i-1] + F[i-2]因此,Fibonacci数列就形如:0, 1, ...