440. 字典序的第K小数字 题解

https://leetcode-cn.com/problems/k-th-smallest-in-lexicographical-order/

#include<bits/stdc++.h>
using namespace std;
int getSteps(int curr, long n) {
    int steps = 0;
    long first = curr;
    long last = curr;
    cout<<"curr="<<curr<<endl;
    while (first <= n) {
        //字典树按层次遍历
        cout<<"first="<<first<<"   last="<<last<<endl;
        steps += min(last, n) - first + 1;
        first = first * 10;
        last = last * 10 + 9;
    }
    return steps;
}

int findKthNumber(int n, int k) {
    int curr = 1;
    k--;
    while (k > 0) {
        int steps = getSteps(curr, n);
        //统计以curr开始的字典树节点数量
        cout<<"steps="<<steps<<endl;
        if (steps <= k) {
            k -= steps;
            curr++;
        } else {
            curr = curr*10;
            k--;
        }
    }
    return curr;
}
int main() {
    //freopen("in.txt","r",stdin);
    cout<<findKthNumber(5000,200)<<endl;
    return 0;
}

 

posted @ 2022-03-24 21:45  shiningrise  阅读(23)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css