题目
字节跳动高频面试题
给定整数 n 和 k,返回 [1, n] 中字典序第 k 小的数字。
思路
如果看作十叉树的先序遍历,遍历到第k位即可
时间复杂度是O(n),我们可以使用count函数,如果子树中的节点数少于k,不再遍历
代码
class Solution {
public:
int findKthNumber(int n, int k) {
long pre=1; // 当前遍历到的数字
int i=0; // 当前遍历到第几个
long cnt;
long ans=pre;
while(i<k){
cnt=count(pre,n);
ans=pre;
if(i+cnt>=k){
pre*=10;
i++;
}else{
pre++;
i+=cnt;
}
}
return ans;
}
long count(int pre,int n){ // 计算以pre为根节点的子树中节点的个数
long cnt=0;
for(long cur=pre,next=pre+1;cur<=n;cur*=10,next*=10){
cnt+=min((long)n+1,next)-cur;
}
return cnt;
}
};