add: 220323-CN [cpp]

This commit is contained in:
Lam Haoyin 2022-03-24 20:13:01 +08:00
parent 0b5c3e48a6
commit 56c767a65a
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
1 changed files with 31 additions and 0 deletions

31
cpp/2203/220323-CN.cpp Normal file
View File

@ -0,0 +1,31 @@
#include <vector>
/**
* 440. K-th Smallest in Lexicographical Order
* Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n].
*/
class Solution {
public:
int findKthNumber(int n, int k) {
auto getCount = [&](int prefix, unsigned long long n) {
auto count = 0ULL;
for (unsigned long long cur = prefix, next = prefix + 1; cur <= n; cur *= 10, next *= 10)
count += std::min(next, n + 1) - cur;
return count;
};
auto p = 1;
auto prefix = 1;
while (p < k) {
auto count = getCount(prefix, n);
if (p + count > k) {
prefix *= 10;
p++;
} else if (p + count <= k) {
prefix++;
p += count;
}
}
return prefix;
}
};