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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lexicographical-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
按字典序排序1到n。
数字优先加0,再往下判断是否大于n
class Solution {
List<Integer> ans = new ArrayList<Integer>();
int n;
public List<Integer> lexicalOrder(int n) {
this.n = n;
for (int i = 1; i <= 9 && i <= n; i++) {
ans.add(i);
addList(i);
}
return ans;
}
public void addList(int num){
for (int i = num * 10; i <= num * 10 + 9 && i <= n; i++) {
ans.add(i);
addList(i);
}
}
}