leetcode386. Dictionary sorting (java)

Question description

Difficulty - Mediumleetcode386
. Dictionary sorting

Given an integer n, return all integers in the range [1, n] in lexicographic order.
You must design an algorithm that takes O(n) time and uses O(1) extra space.

Example 1:
Input: n = 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]

Example 2:
Input: n = 2
Output: [1,2]

Tip:
1 <= n <= 5 * 104

Insert image description here

recursive method

First of all, it is easy to think of using "recursion" to implement DFS.
Adding the numbers [1,n] to the answer in dictionary order is essentially traversing a multi-level tree with a number of nodes and a shape similar to a dictionary tree. The root node is 0 and needs to be skipped, so we can start from The search begins at the second level of the tree.
The value of each node in the tree is the number represented by its search path, and each node has a total of 10 child nodes [0,9].

Code demo:

 List<Integer> ans = new ArrayList<>();
    int _n;
    public List<Integer> lexicalOrder(int n) {
    
    
        _n = n;
        for (int i = 1; i <= 9; i++) dfs(i);
        return ans;
    }
    void dfs(int cur) {
    
    
        if (cur > _n) return ;
        ans.add(cur);
        for (int i = 0; i <= 9; i++) dfs(cur * 10 + i);
    }

Insert image description here

Iterate

There are a total of numbers that need to be processed. Assume that the currently processed number is j. According to the lexicographic order rule, if the conditions are met, we will first add 0 after j (that is, j * 10 < n is satisfied), otherwise we will consider The previous bit goes back and adds one.

Code demo:

 public List<Integer> lexicalOrder(int n) {
    
    
        List<Integer> ans = new ArrayList<>();
        for (int i = 0, j = 1; i < n; i++) {
    
    
            ans.add(j);
            if (j * 10 <= n) {
    
    
                j *= 10;
            } else {
    
    
                while (j % 10 == 9 || j + 1 > n) j /= 10;
                j++;
            }
        }
        return ans;
    }

Guess you like

Origin blog.csdn.net/SP_1024/article/details/132760675