在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Nearly every one have used the Multiplication Table. But could you find out the Given the height 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: 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:
几乎每一个人都用 乘法表。但是你能在乘法表中快速找到第 给定高度 例 1: 输入: m = 3, n = 3, k = 5 输出: 3 解释: 乘法表: 1 2 3 2 4 6 3 6 9 第5小的数字是 3 (1, 2, 2, 3, 3). 例 2: 输入: m = 2, n = 3, k = 6 输出: 6 解释: 乘法表: 1 2 3 2 4 6 第6小的数字是 6 (1, 2, 2, 3, 4, 6). 注意:
Runtime: 52 ms
Memory Usage: 18.5 MB
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 }
|
请发表评论