字典序的第K小数字

链接

给定整数 n 和 k,找到 1 到 n 中字典序第 k 小的数字。

注意:1 ≤ k ≤ n ≤ 109。

import java.util.Scanner;

class Solution {
    public static int findKthNumber(int n, int k) {
        long prefix = 1;
        // 从1出发开始往后按字典序从小到大的顺序走k-1步到达的就是 字典序的第K小数字
        k -= 1;

        while (k > 0) {
            int nodes = getNodes(n, prefix);
            if (k >= nodes) {
                k -= nodes;
                prefix++;
            } else {
                k -= 1;
                prefix *= 10;
            }
        }

        return (int) prefix;
    }

    private static int getNodes(int n, long curPrefix) {
        long nextPrefix = curPrefix + 1;
        long totalNodes = 0;

        while (curPrefix <= n) {
            totalNodes += Math.min(n - curPrefix + 1, nextPrefix - curPrefix);

            nextPrefix *= 10;
            curPrefix *= 10;
        }

        return (int) totalNodes;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(findKthNumber(in.nextInt(), in.nextInt()));
        }
    }
}
posted @ 2021-11-02 12:35  Tianyiya  阅读(92)  评论(0)    收藏  举报