【Leetcode】440. 字典序的第K小数字

555 阅读1分钟

题目描述

在这里插入图片描述

题解

建议直接看大佬讲解 www.bilibili.com/video/BV1q5…

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:35.1 MB, 在所有 Java 提交中击败了74.90%的用户

核心模式

class Solution {
    public int findKthNumber(int n, int k) {
        long cur = 1;
        k -= 1;
        while (k > 0) {
            int nodes = getNodes(n, cur);
            if (nodes <= k) {
                k -= nodes;
                cur++;  // 右移
            }
            else {
                k -= 1;
                cur *= 10;  // 下移
            }
        }
        return (int) cur;
    }
    
    private int getNodes(int n, long cur) {
        long next = cur + 1;
        long totalNodes = 0;
        while (cur <= n) {
            totalNodes += Math.min(next - cur, n - cur + 1);
            cur *= 10;
            next *= 10;
        }
        return (int) totalNodes;
    }
}

ACM

运行时间 35ms

占用内存 12864KB

import java.util.Scanner;

public class Main {
    private static long nodes;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        long n = in.nextLong();  // 不按照Long解析通不过的
        long k = in.nextLong();
        
        long cur = 1;
        k -= 1;
        while (k > 0) {
            nodes = getNodes(n, cur);
            if (nodes <= k) {
                k -= nodes;
                cur++;
            }
            else {
                k -= 1;
                cur *= 10;
            }
        }
        System.out.println(cur);
    }
    
    private static long getNodes(long n, long cur) {
        long next = cur + 1;
        long totalNodes = 0;
        while (cur <=n) {
            totalNodes += Math.min(n - cur + 1, next - cur);
            cur *= 10;
            next *= 10;
        }
        return totalNodes;
    }
}