★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-tdqukcbt-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Nearly every one have used the Multiplication Table. But could you find out the k-th
smallest number quickly from the multiplication table?git
Given the height m
and the length n
of a m * n
Multiplication Table, and a positive integer k
, you need to return the k-th
smallest number in this table.github
Example 1:微信
Input: m = 3, n = 3, k = 5 Output: Explanation: The Multiplication Table: 1 2 3 2 4 6 3 6 9 The 5-th smallest number is 3 (1, 2, 2, 3, 3).
Example 2:ui
Input: m = 2, n = 3, k = 6 Output: Explanation: The Multiplication Table: 1 2 3 2 4 6 The 6-th smallest number is 6 (1, 2, 2, 3, 4, 6).
Note:this
m
and n
will be in the range [1, 30000].k
will be in the range [1, m * n]幾乎每個人都用 乘法表。可是你能在乘法表中快速找到第k
小的數字嗎?spa
給定高度m
、寬度n
的一張 m * n
的乘法表,以及正整數k
,你須要返回表中第k
小的數字。code
例 1:htm
輸入: m = 3, n = 3, k = 5 輸出: 3 解釋: 乘法表: 1 2 3 2 4 6 3 6 9 第5小的數字是 3 (1, 2, 2, 3, 3).
例 2:blog
輸入: m = 2, n = 3, k = 6 輸出: 6 解釋: 乘法表: 1 2 3 2 4 6 第6小的數字是 6 (1, 2, 2, 3, 4, 6).
注意:
m
和 n
的範圍在 [1, 30000] 之間。k
的範圍在 [1, m * n] 之間。1 class Solution { 2 func findKthNumber(_ m: Int, _ n: Int, _ k: Int) -> Int { 3 var left:Int = 1 4 var right:Int = m * n 5 while (left < right) 6 { 7 var mid:Int = left + (right - left) / 2 8 var cnt:Int = 0 9 var i:Int = m 10 var j:Int = 1 11 while (i >= 1 && j <= n) 12 { 13 var t:Int = j 14 j = (mid > n * i) ? n + 1 : (mid / i + 1) 15 cnt += (j - t) * i 16 i = mid / j 17 } 18 if cnt < k 19 { 20 left = mid + 1 21 } 22 else 23 { 24 right = mid 25 } 26 } 27 return right 28 } 29 }
80ms
1 class Solution { 2 func findKthNumber(_ m: Int, _ n: Int, _ k: Int) -> Int { 3 var low = 1, high = m * n 4 while (low <= high) { 5 let mid = low + (high - low) / 2 6 let count = helper(m, n, mid) 7 if count >= k { high = mid - 1 } 8 else { low = mid + 1 } 9 } 10 return low 11 } 12 13 func helper(_ m: Int, _ n: Int, _ num: Int) -> Int { 14 var count = 0 15 let mi = min(m, n), ma = max(m, n) 16 for i in 1...mi { 17 count += min(num / i, ma) 18 } 19 return count 20 } 21 }
92ms
1 class Solution { 2 func findKthNumber(_ m: Int, _ n: Int, _ k: Int) -> Int { 3 var low = 1 4 var high = k 5 6 while low < high { 7 let mid = (low + high) / 2 8 var count = 0 9 for i in 1...m { 10 count += min(mid/i, n) 11 } 12 13 if count < k { 14 low = mid + 1 15 } else { 16 high = mid 17 } 18 } 19 20 return low 21 } 22 }
18348kb
1 class Solution { 2 func findKthNumber(_ m: Int, _ n: Int, _ k: Int) -> Int { 3 var low = 1 4 var high = k 5 6 while low < high { 7 let mid = (low + high) / 2 8 var count = 0 9 for i in 1...m { 10 count += min(mid/i, n) 11 } 12 13 if count >= k { 14 high = mid 15 } else { 16 low = mid + 1 17 } 18 } 19 20 return high 21 } 22 }