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.
一刷
题解:
优先级从大到小:
- *10(保证首部相同)
- 如果个位数字不为9, ++
- 如果为9, 则从个,十, 百,知道找到一个不为9, 取该位+1, 移除为9的位。
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> res = new ArrayList<>(n);
int curr = 1;
for(int i=1; i<=n; i++){
res.add(curr);
if(curr*10<=n) curr = 10*curr;
else if(curr%10 != 9 && curr+1<=n) curr++;
else{
while((curr/10)%10 == 9){
curr /=10;
}
curr = curr/10 + 1;
}
}
return res;
}
}