java: add «440. K-th Smallest in Lexicographical Order»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
2e1df9c0e0
commit
1ac61b1a21
1 changed files with 31 additions and 0 deletions
31
java/k-th-smallest-in-lexicographical-order.java
Normal file
31
java/k-th-smallest-in-lexicographical-order.java
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue