2024-09-21 Daily Challenge
Today I have done leetcode's September LeetCoding Challenge with cpp
.
September LeetCoding Challenge 21
Description
Lexicographical Numbers
Given an integer n
, return all the numbers in the range [1, n]
sorted in lexicographical order.
You must write an algorithm that runs in O(n)
time and uses O(1)
extra space.
Example 1:
Input: n = 13 Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
Example 2:
Input: n = 2 Output: [1,2]
Constraints:
1 <= n <= 5 * 104
Solution
auto speedup = [](){
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
return 0;
}();
class Solution {
public:
vector<int> lexicalOrder(int n) {
int curInt = 1;
vector<int> answer{1};
while(answer.size() < n) {
if(curInt * 10 <= n) {
curInt *= 10;
answer.push_back(curInt);
} else {
while(curInt % 10 == 9 || curInt == n) {
int count = 1;
curInt /= 10;
}
curInt += 1;
answer.push_back(curInt);
}
}
return answer;
}
};