1. 程式人生 > >[LeetCode]440. K-th Smallest in Lexicographical Order

[LeetCode]440. K-th Smallest in Lexicographical Order

求字典序的第k個數


十叉樹,比如10 ~ 20在這一層有10個數,如果20小於n,那麼再找第三層100 ~ 200,每層step就min(n + 1, n2) - n1

public 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 step;
    }
}