1. 程式人生 > >[Swift]LeetCode786. 第 K 個最小的素數分數 | K-th Smallest Prime Fraction

[Swift]LeetCode786. 第 K 個最小的素數分數 | K-th Smallest Prime Fraction

答案 action malle run output smallest ray and tput

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.

一個已排序好的表 A,其包含 1 和其他一些素數. 當列表中的每一個 p<q 時,我們可以構造一個分數 p/q 。

那麽第 k 個最小的分數是多少呢? 以整數數組的形式返回你的答案, 這裏 answer[0] = panswer[1] = q.

示例:
輸入: A = [1, 2, 3, 5], K = 3
輸出: [2, 5]
解釋:
已構造好的分數,排序後如下所示:
1/5, 1/3, 2/5, 1/2, 3/5, 2/3.
很明顯第三個最小的分數是 2/5.

輸入: A = [1, 7], K = 1
輸出: [1, 7]

註意:

  • A 的取值範圍在 22000.
  • 每個 A[i] 的值在 130000.
  • K 取值範圍為 1A.length * (A.length - 1) / 2

Runtime: 64 ms Memory Usage: 19.1 MB
 1 class Solution {
 2     func kthSmallestPrimeFraction(_ A: [Int], _ K: Int) -> [Int] {
 3         var left:Double = 0
 4         var right:Double = 1.0
5 var p:Int = 0 6 var q:Int = 1 7 var cnt:Int = 0 8 var n:Int = A.count 9 while(true) 10 { 11 var mid:Double = left + (right - left) / 2.0 12 cnt = 0 13 p = 0 14 var j:Int = 0 15 for i in 0..<n 16 { 17 while(j < n && Double(A[i]) > mid * Double(A[j])) 18 { 19 j += 1 20 } 21 cnt += n - j 22 if j < n && p * A[j] < q * A[i] 23 { 24 p = A[i] 25 q = A[j] 26 } 27 } 28 if cnt == K {return [p,q]} 29 else if cnt < K {left = mid} 30 else {right = mid} 31 } 32 } 33 }

[Swift]LeetCode786. 第 K 個最小的素數分數 | K-th Smallest Prime Fraction