LeetCode/java/k-th-smallest-in-lexicographical-order.java
2024-09-22 22:14:01 +02:00

31 lines
570 B
Java

class Solution {
private int distance(int upperBound, long left, long right) {
var dist = 0;
for (; left <= upperBound; left *= 10, right *= 10) {
dist += Math.min(upperBound + 1, right) - left;
}
return dist;
}
public int findKthNumber(int n, int k) {
var current = 1;
--k;
while (k > 0) {
var d = distance(n, current, current + 1);
if (d <= k) {
// skipping d numbers at once
++current;
k -= d;
} else {
current *= 10;
--k;
}
}
return current;
}
}