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 ...
随机推荐
- 转:我们是怎么做Code Review的
我们是怎么做Code Review的 前几天看了<Code Review 程序员的寄望与哀伤>,想到我们团队开展Code Review也有2年了,结果还算比较满意,有些经验应该可以和大 ...
- uva 11488 - Hyper Prefix Sets(字典树)
H Hyper Prefix Sets Prefix goodness of a set string is length of longest common prefix*number of str ...
- linked-list-cycle-ii——链表,找出开始循环节点
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull. Follo ...
- 多线程网页爬虫 python 实现(二)
#!/usr/bin/env python #coding=utf-8 import threading import urllib import re import time cur=0 last= ...
- 高速查询hive数据仓库表中的总条数
Author: kwu 高速查询hive数据仓库中的条数.在查询hive表的条数,通常使用count(*).可是数据量大的时候,mr跑count(*)往往须要几分钟的时间. 1.传统方式获得总条数例如 ...
- AJAX核心XMLHTTPRequest对象
老早就写好了总结.今天整理发表一下. XMLHttpRequest对象是AJAX的核心技术,XMLHttpRequest 是XMLHTTP 组件的对象,通过这个对象.AJAX能够像桌面应用程序一样仅仅 ...
- Appium,IOS 模拟器,Java工程搭建
首先进入sample code Test App 有TestApp.xcodeproj文件的工程目录下 下编译出TestApp.app文件 1.新建 java 工程 2.import需要的包 新建cl ...
- 时光轴一之listView实现时光轴效果
尼玛.非要搞什么时光轴,一想简单的不就是个listView吗,然后一步一步来就好了,哈哈别看那么好看事实上不要想多了. 时光轴timeline最大的作用就是把过去的事物系统化.完整化.精确化.时间轴可 ...
- 设置label的字体
label.font = [UIFont fontWithName:@"Arial-BoldItalicMT" size:24]; 字体名如下: Font Family: Amer ...
- bzoj2436: [Noi2011]Noi嘉年华
我震惊了,我好菜,我是不是该退役(苦逼) 可以先看看代码里的注释 首先我们先考虑一下第一问好了真做起来也就这个能想想了 那么离散化时间是肯定的,看一手范围猜出是二维DP,那对于两个会场,一个放自变量, ...