Description:
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:
非独自完成,思路很巧妙。
class Solution { public List<Integer> lexicalOrder(int n) { List<Integer> list = new ArrayList<Integer>(); int res = 1; for(int i = 1; i<=n; i++){ list.add(res); if(res*10<=n){ res = res *10; } else if( res%10 !=9 && res +1 <=n){ res++; } else{ while((res/10)%10==9){ res = res/10; } res = res/10 + 1; } } return list; } }