Problem:
Given an integer n, return 1 - n in lexicographical order.
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
思路:
Solution (C++):
vector lexicalOrder(int n) {
vector res;
helper(1, n, res);
return res;
}
void helper(int target, int n, vector& res) {
if (target > n) return;
res.push_back(target);
helper(target*10, n, res);
if (target % 10 != 9) helper(target+1, n, res);
}
性能:
Runtime: 68 ms Memory Usage: 9.8 MB
思路:
Solution (C++):
vector lexicalOrder(int n) {
vector res(n, 0);
int cur = 1;
for (int i = 0; i < n; ++i) {
res[i] = cur;
if (cur * 10 <= n) cur *= 10;
else {
if (cur >= n) cur /= 10;
++cur;
while (cur%10 == 0) cur /= 10;
}
}
return res;
}
性能:
Runtime: 60 ms Memory Usage: 8.7 MB