Lexicographical Numbers

LeetCode Q 386 - Lexicographical Numbers

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.

Solution

Solution 1: Sort O(nlogn)

Code:

public List<Integer> lexicalOrder(int n) {
  List<Integer> list = new ArrayList<>();
  
  for (int i = 1; i <= n; i++) list.add(i);

  Collections.sort(list, (a, b) -> {
    return String.valueOf(a).compareTo(String.valueOf(b));
  });

  return list;
}

Solution 2: DFS O(n)

Code:

List<Integer> list;
public List<Integer> lexicalOrder(int n) {
  list = new ArrayList<>();
  
  for (int i = 1; i <= 9; i++) {
    if (i > n) break;
    dfs(n, i);
  }

  return res;
}

private void dfs(int n, int currNum) {
  res.add(current);
  for (int i = 0; i <= 9; i++) {
    if (currNum * 10 + i > n) break;
    dfs(n, currNum * 10 + i);
  }
}

   Reprint policy


《Lexicographical Numbers》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
 Previous
Insufficient Nodes in Root to Leaf Paths Insufficient Nodes in Root to Leaf Paths
LeetCode Q 1080 - Insufficient Nodes in Root to Leaf PathsGiven the root of a binary tree, consider all root to leaf pat
2019-08-15 Tong Shi
Next 
Shifting Letters Shifting Letters
LeetCode Q 848 - Shifting LettersWe have a string S of lowercase letters, and an integer array shifts.Call the shift of
2019-08-15 Tong Shi
  TOC