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. 谜题 之 C语言

    本篇文章展示了14个C语言的迷题以及答案.代码应该是足够清楚的,并且我也相信有相当的一些样例可能是我们日常工作可能会见得到的.通过这些迷题,希望你能更了解C语言.假设你不看答案.不知道是否有把握回答各 ...

  2. JAVA设计模式之单例模式(转)

    本文继续介绍23种设计模式系列之单例模式. 概念: java中单例模式是一种常见的设计模式,单例模式的写法有好几种,这里主要介绍三种:懒汉式单例.饿汉式单例.登记式单例. 单例模式有以下特点: 1.单 ...

  3. WebService Get/Post/Soap 方式请求

    import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.InputStream; im ...

  4. 混合minxins

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. java设计模式----复合模式

    复合模式:复合模式结合两个或以上的模式,组成一个解决方案,解决一再发生的一般性问题 要点: 1.MVC是复合模式,结合了观察者模式.策略模式和组合模式 2.模型使用观察者模式,以便观察者更新,同时保持 ...

  6. 模式识别之聚类算法k-均值---k-均值聚类算法c实现

    //写个简单的先练习一下,测试通过 //k-均值聚类算法C语言版   #include <stdlib.h>      #include <stdio.h>      #inc ...

  7. Thread Runnable 区别

    [线程的并发与并行] 在单CPU系统中,系统调度在某一时刻只能让一个线程运行,虽然这种调试机制有多种形式(大多数是时间片轮巡为主),但无论如何,要通过不断切换需要运行的线程让其运行的方式就叫并发(co ...

  8. fstab文件解析

    1 这个文件的用途 这个文件是启动时自动挂载指定的磁盘或者分区到系统目录下用的,提供给mount命令用. 2 文件解析 每一行是一次mount操作. 磁盘或者分区    挂载的目录     挂载的磁盘 ...

  9. js对table操作(添加删除交换上下TR)

    <table width="100%" border="0" cellpadding="2" cellspacing="1& ...

  10. javascript数据基本类型和引用类型

    JavaScript基本数据类型: js基本数据类型包括:undefined,null,number,boolean,string.基本数据类型是按值访问的,就是说我们可以操作保存在变量中的实际的值. ...