classSolution: deflexicalOrder(self, n: int) -> List[int]: ans = [0] * n num = 1 for i inrange(n): ans[i] = num if num * 10 <= n: num *= 10 else: while num % 10 == 9or num + 1 > n: num //= 10 num += 1 return ans
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: vector<int> lexicalOrder(int n){ vector<int> ret(n); int number = 1; for (int i = 0; i < n; i++) { ret[i] = number; if (number * 10 <= n) { number *= 10; } else { while (number % 10 == 9 || number + 1 > n) { number /= 10; } number++; } } return ret; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public List<Integer> lexicalOrder(int n) { List<Integer> ret = newArrayList<Integer>(); intnumber=1; for (inti=0; i < n; i++) { ret.add(number); if (number * 10 <= n) { number *= 10; } else { while (number % 10 == 9 || number + 1 > n) { number /= 10; } number++; } } return ret; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicclassSolution { public IList<int> LexicalOrder(int n) { IList<int> ret = new List<int>(); int number = 1; for (int i = 0; i < n; i++) { ret.Add(number); if (number * 10 <= n) { number *= 10; } else { while (number % 10 == 9 || number + 1 > n) { number /= 10; } number++; } } return ret; } }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int* lexicalOrder(int n, int* returnSize){ int *ret = (int *)malloc(sizeof(int) * n); int number = 1; for (int i = 0; i < n; i++) { ret[i] = number; if (number * 10 <= n) { number *= 10; } else { while (number % 10 == 9 || number + 1 > n) { number /= 10; } number++; } } *returnSize = n; return ret; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var lexicalOrder = function(n) { const ret = []; let number = 1; for (let i = 0; i < n; i++) { ret.push(number); if (number * 10 <= n) { number *= 10; } else { while (number % 10 === 9 || number + 1 > n) { number = Math.floor(number / 10); } number++; } } return ret; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funclexicalOrder(n int) []int { ans := make([]int, n) num := 1 for i := range ans { ans[i] = num if num*10 <= n { num *= 10 } else { for num%10 == 9 || num+1 > n { num /= 10 } num++ } } return ans }
复杂度分析
时间复杂度:$O(n)$,其中 $n$ 为整数的数目。获取下一个字典序整数的最坏时间复杂度为 $O(\log n)$,但 while 循环的迭代次数与 number 的末尾连续的 $9$ 的数目有关,在整数区间 $[1, n]$ 中,末尾连续的 $9$ 的数目为 $k$ 的整数不超过 $\Big \lceil \dfrac{n}{10^k} \Big \rceil$ 个,其中 $1 \le k \le \lceil \log_{10} n \rceil$,因此总迭代次数不超过 $\sum_k k \Big \lceil \dfrac{n}{10^k} \Big \rceil \le 2n$,总时间复杂度为 $O(n)$。