440. K-th Smallest in Lexicographical Order
https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/
/*
* @lc app=leetcode id=440 lang=cpp
*
* [440] K-th Smallest in Lexicographical Order
*/
// @lc code=start
class Solution {
public:
int findKthNumber(int n, int k) {
const auto find_gap = [](long a, long b, long n) {
// a = 1, b = 2, n = 198, gap = 1
// a = 13, b = 20 gap = 10 + 1
// a = 100, b = 200, gap = 199 - 100 + 11 = 120
long gap = 0;
while (a <= n) {
gap += min(n + 1, b) - a;
a *= 10;
b *= 10;
}
return gap;
};
long cur = 1;
while (k > 1) {
long gap = find_gap(cur, cur + 1, n);
if (gap <= k - 1) {
k -= gap;
++cur;
} else {
cur *= 10;
--k;
}
}
return (int)cur;
}
};
// @lc code=end
Last updated