Very Easy Java O(n) Iterative Solution


  • 0
    A
    public List<Integer> lexicalOrder(int n) {
        List<Integer> res = new ArrayList<>();
        if (n == 0)   return res;
        
        int num = 1;
        res.add(num);
        
        while (res.size() < n) {    
            if (num * 10 <= n) {
                num = num * 10;
            }
            else {
                num++;
                if (num > n) {
                    num--;
                    num /= 10;
                    num++;
                }
                while (num % 10 == 0) {
                    num /= 10;
                }
            }
            res.add(num);
        }
        return res;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.