386. Lexicographical Numbers

来源:互联网 发布:淘宝大数据 编辑:程序博客网 时间:2024/06/10 16:11

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.

Subscribe to see which companies asked this question.

在没看别人的方法之前,自己写的方法时间超时了。

如果当前数是a,则a下个数可能为10*a(10*<n),a+1(a的最后一位不为9),a/10+1(a的最后一位为9).。

public class Solution {    public List<Integer> lexicalOrder(int n) {        LinkedList<Integer> list=new LinkedList<>();        int cur=1;        for (int i = 1; i <=n ; i++) {            list.add(cur);            if (10 * cur <= n) {                cur *= 10;            } else if (cur % 10 != 9 && cur + 1 <= n) {                cur++;            } else {                while ((cur / 10) % 10 == 9) {                    cur /= 10;                }                cur = cur / 10 + 1;            }        }        return list;    }}




0 0