leetcode 386. Lexicographical Numbers

来源:互联网 发布:hecras软件中堰流系数 编辑:程序博客网 时间:2024/05/17 21:47

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.


这道题思路就是将以1开头的数字、以2开头的数字、.......以9开头的数字分开来。然后以1开头的数字为例,我们在其后的每个数字后加上0~9。就像下图的树一样。


public List<Integer> lexicalOrder(int n) {List<Integer> list=new ArrayList<Integer>();for(int i=1;i<=9;i++){helper(i, n, list);}return list;}public void helper(int number,int n,List<Integer> list){if(number>n){return;}else{list.add(number);for(int i=0;i<=9;i++){helper(10*number+i, n, list);}}return;}
大神则用了时间复杂度为O(n) , 空间复杂度为O(1) 的迭代方法。
public List<Integer> lexicalOrder(int n) {        List<Integer> list = new ArrayList<>(n);        int curr = 1;        for (int i = 1; i <= n; i++) {            list.add(curr);            if (curr * 10 <= n) {                curr *= 10;            } else if (curr % 10 != 9 && curr + 1 <= n) {                curr++;            } else {                while ((curr / 10) % 10 == 9) {                    curr /= 10;                }                curr = curr / 10 + 1;            }        }        return list;}
思路是找到:往 list 中加的后一个元素。
以当前数字为45来举个例子: 如果当前数字是45,那么下一个数字将是450 (450 == 45 * 10)(if 450 <= n), 或者 46 (46 == 45 + 1) (if 450>n and 46 <= n) 或者 5 (5 == 45 / 10 + 1) (因为5<45,所以肯定5<n).
又以 n = 600 来举个例子, 如果当前数字是 499, 那么下一个数字是5,因为在499中 "4" 后面全是 “9”,所以要一直用10来除499,直到下一个数字不是9。


原创粉丝点击