0
点赞
收藏
分享

微信扫一扫

440. K-th Smallest in Lexicographical Order


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.

思路:
比如10 ~ 20在这一层有10个数,如果20小于n,那么再找第三层100 ~ 200,每层step就min(n + 1, n2) - n1。

class Solution {
public int findKthNumber(int n, int k) {
int cur = 1;
int step;
k--;
while (k > 0) {
step = calStep(n, cur, cur + 1);
if (step <= k) {
k -= step;
cur++;
} else {
k--;
cur *= 10;
}
}
return cur;
}

private int calStep(int n, long n1, long n2) {
int step = 0;
while (n1 <= n) {
step += Math.min(n + 1, n2) - n1;
n1 *= 10;
n2 *= 10;
}
return


举报

相关推荐

0 条评论