在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ A sorted list What is the 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 = [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] 注意:
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 }
|
请发表评论