440:字典序的第K小数字
This commit is contained in:
parent
30a2f7e492
commit
6a240fe01c
@ -0,0 +1,75 @@
|
||||
//给定整数 n 和 k,返回 [1, n] 中字典序第 k 小的数字。
|
||||
//
|
||||
//
|
||||
//
|
||||
// 示例 1:
|
||||
//
|
||||
//
|
||||
//输入: n = 13, k = 2
|
||||
//输出: 10
|
||||
//解释: 字典序的排列是 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],所以第二小的数字是 10。
|
||||
//
|
||||
//
|
||||
// 示例 2:
|
||||
//
|
||||
//
|
||||
//输入: n = 1, k = 1
|
||||
//输出: 1
|
||||
//
|
||||
//
|
||||
//
|
||||
//
|
||||
// 提示:
|
||||
//
|
||||
//
|
||||
// 1 <= k <= n <= 10⁹
|
||||
//
|
||||
// Related Topics 字典树 👍 389 👎 0
|
||||
|
||||
package leetcode.editor.cn;
|
||||
|
||||
//440:字典序的第K小数字
|
||||
public class KThSmallestInLexicographicalOrder {
|
||||
public static void main(String[] args) {
|
||||
Solution solution = new KThSmallestInLexicographicalOrder().new Solution();
|
||||
// TO TEST
|
||||
System.out.println(solution.findKthNumber(13, 2));
|
||||
System.out.println(solution.findKthNumber(1, 1));
|
||||
System.out.println(solution.findKthNumber(100, 90));
|
||||
System.out.println(solution.findKthNumber(10000, 10000));
|
||||
}
|
||||
|
||||
//leetcode submit region begin(Prohibit modification and deletion)
|
||||
class Solution {
|
||||
public int findKthNumber(int n, int k) {
|
||||
for (int i = 1; i <= n; i++) {
|
||||
if (k == 1) {
|
||||
return i;
|
||||
}
|
||||
int count = getCount(i, n);
|
||||
if (count < k) {
|
||||
k -= count;
|
||||
} else {
|
||||
i = i * 10 - 1;
|
||||
k--;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getCount(int num, long n) {
|
||||
int count = 0;
|
||||
long min = num;
|
||||
long max = num;
|
||||
while (min <= n) {
|
||||
count += Math.min(max, n) - min + 1;
|
||||
min = min * 10;
|
||||
max = max * 10 + 9;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
}
|
||||
//leetcode submit region end(Prohibit modification and deletion)
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
<p>给定整数 <code>n</code> 和 <code>k</code>,返回 <code>[1, n]</code> 中字典序第 <code>k</code> 小的数字。</p>
|
||||
|
||||
<p> </p>
|
||||
|
||||
<p><strong>示例 1:</strong></p>
|
||||
|
||||
<pre>
|
||||
<strong>输入: </strong>n = 13, k = 2
|
||||
<strong>输出: </strong>10
|
||||
<strong>解释: </strong>字典序的排列是 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],所以第二小的数字是 10。
|
||||
</pre>
|
||||
|
||||
<p><strong>示例 2:</strong></p>
|
||||
|
||||
<pre>
|
||||
<strong>输入:</strong> n = 1, k = 1
|
||||
<strong>输出:</strong> 1
|
||||
</pre>
|
||||
|
||||
<p> </p>
|
||||
|
||||
<p><strong>提示:</strong></p>
|
||||
|
||||
<ul>
|
||||
<li><code>1 <= k <= n <= 10<sup>9</sup></code></li>
|
||||
</ul>
|
||||
<div><div>Related Topics</div><div><li>字典树</li></div></div><br><div><li>👍 389</li><li>👎 0</li></div>
|
Loading…
Reference in New Issue
Block a user