java: add «440. K-th Smallest in Lexicographical Order»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-22 22:14:01 +02:00
parent 2e1df9c0e0
commit 1ac61b1a21
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,31 @@
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;
}
}