Java Stack solution(442 ms)


  • 0
    J
    public class Solution {
        public List<Integer> lexicalOrder(int n) {
            List<Integer> result = new ArrayList<>();
            Stack<Integer> stack = new Stack<>();
            stack.add(1);
            while (!stack.isEmpty()) {
                int current = stack.peek();
                result.add(current);
                if (current * 10 <= n) {
                    stack.add(current * 10);
                } else {
                    stack.pop();
                    if (current + 1 < (current / 10) * 10 + 10 && current + 1 <= n) {
                        stack.add(current + 1);
                    } else {
                        while (!stack.isEmpty()) {
                            int parent = stack.pop();
                            if (parent + 1 < (parent / 10) * 10 + 10 && parent + 1 <= n) {
                                stack.add(parent + 1);
                                break;
                            }
                        }
                    }
    
                }
            }
    
            return result;
        }
    
    }
    
    

Log in to reply
 

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