字典序最小的K个数字
typedef long long LL;
class Solution {
public:
int findKthNumber(int n, int k) {
int prefix = 1;
k--;
while(k>0){
int cnt = getCnt(n,prefix);
if(cnt<=k){
k-=cnt;
prefix++;
}else{
k--;
prefix*=10;
}
}
return prefix;
}
int getCnt(LL n,LL prefix){
LL cnt = 0;
for(LL first=prefix,second=prefix+1;first<=n;first*=10,second*=10){
cnt += min(n+1,second) - first;
}
return cnt;
}
};算法小屋 文章被收录于专栏
不定期分享各类算法以及面经。同时也正在学习相关分布式技术。欢迎一起交流。
查看12道真题和解析

