给定一个整数 n, 返回从 1 到 n 的字典顺序。
例如,
给定 n =1 3,返回 [1,10,11,12,13,2,3,4,5,6,7,8,9] 。
请尽可能的优化算法的时间复杂度和空间复杂度。 输入的数据 n 小于等于 5,000,000。
class Solution {
vector<int>res;
public:
vector<int> lexicalOrder(int n) {
for(int i=1;i<=9&&i<=n;++i)
backTrack(i,n);
return res;
}
void backTrack(int path,int &n){
res.push_back(path);
for(int i=0;i<=9&&path*10+i<=n;++i)
backTrack(path*10+i,n);
}
};
给定整数 n 和 k,找到 1 到 n 中字典序第 k 小的数字。
注意:1 ≤ k ≤ n ≤ 109。
示例 :
输入:
n: 13 k: 2
输出:
10
解释:
字典序的排列是 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],所以第二小的数字是 10。
//https://leetcode-cn.com/problems/k-th-smallest-in-lexicographical-order/solution/ben-ti-shi-shang-zui-wan-zheng-ju-ti-de-shou-mo-sh/
class Solution {
public:
int findKthNumber(int n, int k) {
long long prefix=1,cnt=1;
while(cnt<k){
long long count=getCnt(prefix,n);
if(k>=cnt+count){
cnt+=count;
++prefix;
}
else{
++cnt;
prefix*=10;
}
}
return prefix;
}
long long getCnt(long long prefix,long long n){
long long cnt=0;
long long next=prefix+1;
while(prefix<=n){
cnt+=min(n+1,next)-prefix;
prefix*=10;
next*=10;
}
return cnt;
}
};