• Leetcode: 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 1: 

    If we look at the order we can find out we just keep adding digit from 0 to 9 to every digit and make it a tree.
    Then we visit every node in pre-order. 
           1        2        3    ...
          /        /       /
       10 ...19  20...29  30...39   ....


     1 public class Solution {
     2     public List<Integer> lexicalOrder(int n) {
     3         ArrayList<Integer> res = new ArrayList<Integer>();
     4         for (int i=1; i<=9; i++) {
     5             helper(res, i, n);
     6         }
     7         return res;
     8     }
     9     
    10     public void helper(ArrayList<Integer> res, int cur, int n) {
    11         if (cur > n) return;
    12         res.add(cur);
    13         for (int i=0; i<=9; i++) {
    14             helper(res, cur*10+i, n);
    15         }
    16     }
    17 }

    Solution 2: 

    O(N) time, O(1) space

    The basic idea is to find the next number to add.
    Take 45 for example: if the current number is 45, the next one will be 450 (450 == 45 * 10)(if 450 <= n), or 46 (46 == 45 + 1) (if 46 <= n) or 5 (5 == 45 / 10 + 1)(5 is less than 45 so it is for sure less than n).
    We should also consider n = 600, and the current number = 499, the next number is 5 because there are all "9"s after "4" in "499" so we should divide 499 by 10 until the last digit is not "9".

    Note: 第二、三种情况不能合并的原因是:不一定是因为最后一位是9才需要/10,有可能是因为curr+1>n

     1 public List<Integer> lexicalOrder(int n) {
     2         List<Integer> list = new ArrayList<>(n);
     3         int curr = 1;
     4         for (int i = 1; i <= n; i++) {
     5             list.add(curr);
     6             if (curr * 10 <= n) {
     7                 curr *= 10;
     8             } else if (curr % 10 != 9 && curr + 1 <= n) {
     9                 curr++;
    10             } else {
    11                 while ((curr / 10) % 10 == 9) {
    12                     curr /= 10;
    13                 }
    14                 curr = curr / 10 + 1;
    15             }
    16         }
    17         return list;
    18     }
  • 相关阅读:
    ERP类系统设计学习
    人工智能关键词
    系统性能
    连接不同服务器不同数据库
    socket一个例子
    SQLite
    asp.net 页面缓存、数据缓存
    原生js
    Android 网络调试 adb tcpip 开启方法
    C语言中string char int类型转换
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6113025.html
Copyright © 2020-2023  润新知