Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.
Note: 1 ≤ k ≤ n ≤ 109.
Example:
Input: n: 13 k: 2 Output: 10 Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
思路一:直接遍历求解,会TLE,程序如下所示:
class Solution {
public int findKthNumber(int n, int k) {
int cnt = 0, index = 1;
for (int i = 1; i <= n; ++ i){
cnt ++;
if (cnt == k){
return index;
}
if ((long)index*10 <= (long)n){
index *= 10;
}
else {
if (index + 1 > n){
index = index/10;
}
else {
if ((index%10) == 9){
while ((index%10) == 9){
index = index/10;
}
}
}
index ++;
}
}
return cnt;
}
}
思路2:本例其实可以看成一颗10叉数,链接点击打开,程序如下所示:
class Solution {
public int getCount(int p, int q, int n){
int result = 0;
long a = (long)p, b = (long)q;
while (a <= n){
result += Math.min(b, n+1) - a;
a *= 10;
b *= 10;
}
return result;
}
public int findKthNumber(int n, int k) {
int result = 1;
while (k > 1){
int count = getCount(result, result + 1, n);
if (count < k){
result += 1;
k -= count;
}
else {
result *= 10;
k --;
}
}
return result;
}
}
本文介绍了一种高效算法,用于找到从1到n范围内字典序第K小的整数。通过构建一棵10叉树,并利用递归计数方法,解决了传统遍历方法效率低下的问题。
2980

被折叠的 条评论
为什么被折叠?



