440:字典序的第K小数字

This commit is contained in:
轩辕龙儿 2022-03-23 17:24:56 +08:00
parent 30a2f7e492
commit 6a240fe01c
2 changed files with 102 additions and 0 deletions

View File

@ -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)
}

View File

@ -0,0 +1,27 @@
<p>给定整数&nbsp;<code>n</code>&nbsp;&nbsp;<code>k</code>,返回&nbsp;&nbsp;<code>[1, n]</code>&nbsp;中字典序第&nbsp;<code>k</code>&nbsp;小的数字。</p>
<p>&nbsp;</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>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= k &lt;= n &lt;= 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>