原题链接在这里:https://leetcode.com/problems/lexicographical-numbers/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.
题解:
从cur=1开始加入res中,下个数有三种情况:
第一种, cur*10 <= n, 就把cur 乘以 10.
第二种, cur 末位不是9 并且 cur+1<=n的情况下, cur++.
第三种, 末位已经等于9, 或者cur现在增加到n, 此时把cur调整到前一位不为9的level.
Time Complexity: O(n). Space: O(1).
AC Java:
1 class Solution { 2 public List<Integer> lexicalOrder(int n) { 3 List<Integer> res = new ArrayList<Integer>(); 4 int cur = 1; 5 for(int i = 0; i<n; i++){ 6 res.add(cur); 7 if(cur*10 <= n){ 8 cur *= 10; 9 }else if(cur%10!=9 && cur<n){ 10 cur++; 11 }else{ 12 while((cur/10)%10 == 9){ 13 cur /= 10; 14 } 15 cur = cur/10+1; 16 } 17 } 18 return res; 19 } 20 }