LeetCode Lexicographical Numbers

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Lexicographical Numbers相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/lexicographical-numbers/description/

题目:

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.

题解:

从cur=1开始加入res中,下个数有三种情况:

第一种, cur*10 <= n, 就把cur 乘以 10.

第二种, cur 末位不是9 并且 cur+1<=n的情况下, cur++.

第三种, 末位已经等于9, 或者cur现在增加到n, 此时把cur调整到前一位不为9的level.

Time Complexity: O(n). Space: O(1).

AC Java: 

 1 class Solution {
 2     public List<Integer> lexicalOrder(int n) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         int cur = 1;
 5         for(int i = 0; i<n; i++){
 6             res.add(cur);
 7             if(cur*10 <= n){
 8                 cur *= 10;
 9             }else if(cur%10!=9 && cur<n){
10                 cur++;
11             }else{
12                 while((cur/10)%10 == 9){
13                     cur /= 10;
14                 }
15                 cur = cur/10+1;
16             }
17         }
18         return res;
19     }
20 }

 

以上是关于LeetCode Lexicographical Numbers的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode: Lexicographical Numbers

LeetCode-Lexicographical Numbers

(Java) LeetCode 386. Lexicographical Numbers —— 字典序排数

Leetcode: K-th Smallest in Lexicographical Order

[LeetCode] K-th Smallest in Lexicographical Order 字典顺序的第K小数字

lexicographical-numbers