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:

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

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:

  1. static_cast<>() gives you a compile time checking ability, C-Style cast doesn't.
  2. static_cast<>() can be spotted easily anywhere inside a C++ source code; in contrast, C_Style cast is harder to spot.
  3. 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 bytes

Since 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 corruption

In 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的更多相关文章

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

  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】堆 heap(共31题)

    链接:https://leetcode.com/tag/heap/ [23] Merge k Sorted Lists [215] Kth Largest Element in an Array (无 ...

  5. 【LeetCode】二分 binary_search(共58题)

    [4]Median of Two Sorted Arrays [29]Divide Two Integers [33]Search in Rotated Sorted Array [34]Find F ...

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

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

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

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

随机推荐

  1. uva 11468 - Substring(AC自己主动机+概率)

    题目链接:uva 11468 - Substring 题目大意:给出一些字符和各自字符相应的选择概率.随机选择L次后得到一个长度为L的字符串,要求该字符串不包括随意一个子串的概率. 解题思路:构造AC ...

  2. UUID GUID

    http://baike.baidu.com/link?url=xkck9gR5bzOx0oBKP1qNJwGGq3IO56V4i8cg9zTSpSDMVBMA0F7jr0AdkQTGyk7F0FGj ...

  3. Intel Naming Strategy--1

    http://en.wikipedia.org/wiki/Mobile_Internet_device Computer sizes   Classes of computers   Larger S ...

  4. Linux安装配置Redis CentOS 7 下安装Redis

    Redis是一个高性能的,开源key-value型数据库.是构建高性能,可扩展的Web应用的完美解决方案,可以内存存储亦可持久化存储.因为要使用跨进程,跨服务级别的数据缓存,在对比多个方案后,决定使用 ...

  5. Codeforces Round #422 (Div. 2) C. Hacker, pack your bags! 排序,贪心

    C. Hacker, pack your bags!     It's well known that the best way to distract from something is to do ...

  6. java中方法中声明三个点“...”作用

    public class Test {  public static void main(String[] args) {   String str[] = {"s"," ...

  7. 怎样在QML中利用Sprite来做我们须要的动画

    在游戏中动画的设计很中要. 在QML中,它提供了丰富的animation.可是有时我们须要对图像进行变化,就像放电影一样.在今天的这篇文章中,我们将设计一个能够变化图像的动画. 我们能够通过Qt所提供 ...

  8. bashdb bashdebug

    sudo  apt-get install bashdb bashdb  --debug 一.列出代码和查询代码类: l 列出当前行以下的10行 - 列出正在执行的代码行的前面10行 . 回到正在执行 ...

  9. amazon lightsail

    https://51.ruyo.net/6038.html https://aws.amazon.com/cn/lightsail/

  10. 计算机学院大学生程序设计竞赛(2015’12)Study Words

    Study Words Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Tota ...