|
48 | 48 |
|
49 | 49 | <!-- 这里可写通用的实现逻辑 -->
|
50 | 50 |
|
| 51 | +**方法一:二分查找** |
| 52 | + |
| 53 | +题目可以转换为,求有多少个数不超过 x。对于每一行 i,所有数都是 i 的倍数,不超过 x 的个数有 `x / i` 个。 |
| 54 | + |
| 55 | +二分枚举 x,累加每一行不超过 x 的个数,得到 cnt。找到 `cnt >= k` 的最小 x。 |
| 56 | + |
51 | 57 | <!-- tabs:start -->
|
52 | 58 |
|
53 | 59 | ### **Python3**
|
54 | 60 |
|
55 | 61 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
56 | 62 |
|
57 | 63 | ```python
|
58 |
| - |
| 64 | +class Solution: |
| 65 | + def findKthNumber(self, m: int, n: int, k: int) -> int: |
| 66 | + left, right = 1, m * n |
| 67 | + while left < right: |
| 68 | + mid = (left + right) >> 1 |
| 69 | + cnt = 0 |
| 70 | + for i in range(1, m + 1): |
| 71 | + cnt += min(mid // i, n) |
| 72 | + if cnt >= k: |
| 73 | + right = mid |
| 74 | + else: |
| 75 | + left = mid + 1 |
| 76 | + return left |
59 | 77 | ```
|
60 | 78 |
|
61 | 79 | ### **Java**
|
62 | 80 |
|
63 | 81 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
64 | 82 |
|
65 | 83 | ```java
|
| 84 | +class Solution { |
| 85 | + public int findKthNumber(int m, int n, int k) { |
| 86 | + int left = 1, right = m * n; |
| 87 | + while (left < right) { |
| 88 | + int mid = (left + right) >>> 1; |
| 89 | + int cnt = 0; |
| 90 | + for (int i = 1; i <= m; ++i) { |
| 91 | + cnt += Math.min(mid / i, n); |
| 92 | + } |
| 93 | + if (cnt >= k) { |
| 94 | + right = mid; |
| 95 | + } else { |
| 96 | + left = mid + 1; |
| 97 | + } |
| 98 | + } |
| 99 | + return left; |
| 100 | + } |
| 101 | +} |
| 102 | +``` |
| 103 | + |
| 104 | +### **C++** |
| 105 | + |
| 106 | +```cpp |
| 107 | +class Solution { |
| 108 | +public: |
| 109 | + int findKthNumber(int m, int n, int k) { |
| 110 | + int left = 1, right = m * n; |
| 111 | + while (left < right) |
| 112 | + { |
| 113 | + int mid = (left + right) >> 1; |
| 114 | + int cnt = 0; |
| 115 | + for (int i = 1; i <= m; ++i) cnt += min(mid / i, n); |
| 116 | + if (cnt >= k) right = mid; |
| 117 | + else left = mid + 1; |
| 118 | + } |
| 119 | + return left; |
| 120 | + } |
| 121 | +}; |
| 122 | +``` |
66 | 123 |
|
| 124 | +### **Go** |
| 125 | +
|
| 126 | +```go |
| 127 | +func findKthNumber(m int, n int, k int) int { |
| 128 | + left, right := 1, m*n |
| 129 | + for left < right { |
| 130 | + mid := (left + right) >> 1 |
| 131 | + cnt := 0 |
| 132 | + for i := 1; i <= m; i++ { |
| 133 | + cnt += min(mid/i, n) |
| 134 | + } |
| 135 | + if cnt >= k { |
| 136 | + right = mid |
| 137 | + } else { |
| 138 | + left = mid + 1 |
| 139 | + } |
| 140 | + } |
| 141 | + return left |
| 142 | +} |
| 143 | +
|
| 144 | +func min(a, b int) int { |
| 145 | + if a < b { |
| 146 | + return a |
| 147 | + } |
| 148 | + return b |
| 149 | +} |
67 | 150 | ```
|
68 | 151 |
|
69 | 152 | ### **...**
|
|
0 commit comments