题目描述
题解
建议直接看大佬讲解
https://www.bilibili.com/video/BV1q5411A7fU?spm_id_from=333.999.0.0
执行用时: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); // Math.min(n在cur树内, n在cur树外)
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;
}
}
/
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static long n;
public static long k;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLong()) {
n = in.nextLong();
k = in.nextLong();
}
long cur = 1;
k -= 1;
while (k > 0) {
long nodes = getNodes(n, cur);
if (nodes <= k) {
k -= nodes;
cur++; // 右移
}
else {
k -= 1;
cur *= 10; // 下移
}
}
System.out.println(cur);
}
public static long getNodes(long n, long cur) {
long totalNodes = 0;
long next = cur + 1;
while (cur <= n) {
totalNodes += Math.min(n - cur + 1, next - cur);
cur *= 10;
next *= 10;
}
return totalNodes;
}
}