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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-fuzqwqjk-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

What is the K-th smallest fraction considered?  Return your answer as an array of ints, where answer[0] = p and answer[1] = q.github

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] = p 且 answer[1] = q.ide

示例:
輸入: 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]

注意:spa

  • A 的取值範圍在 2 — 2000.
  • 每一個 A[i] 的值在 1 —30000.
  • K 取值範圍爲 1 —A.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 }
相關文章
相關標籤/搜索