当前位置:网站首页>386. 字典序排数(中等)-迭代-全排列
386. 字典序排数(中等)-迭代-全排列
2022-04-23 17:32:00 【hequnwang10】
一、题目描述
给你一个整数 n ,按字典序返回范围 [1, n] 内所有整数。
你必须设计一个时间复杂度为 O(n) 且使用 O(1) 额外空间的算法。
示例 1:
输入:n = 13
输出:[1,10,11,12,13,2,3,4,5,6,7,8,9]
示例 2:
输入:n = 2
输出:[1,2]
二、解题
迭代
共有 n 个数需要被处理,假设当前处理到的数为 j,根据字典序规则,在满足条件的前提下,我们优先在 j 的后面添加 0(即 j * 10 < n 满足),否则我们考虑将上一位回退并进行加一操作。
class Solution {
public List<Integer> lexicalOrder(int n) {
//迭代
List<Integer> res = new ArrayList<>();
int number = 1;
for(int i = 0;i<n;i++){
res.add(number);
//首先尝试在number后面加0
if(number * 10 <= n){
number *= 10;
}else{
//如果加0后大于n了,则每次只加1.当然也需要判断是否进位 比如19,29,39。。。达到进位要求然后回退上一位。
while( number % 10 == 9 || number+1>n){
number /= 10;
}
number++;
}
}
return res;
}
}
时间复杂度:O(n);
空间复杂度:O(1)。
版权声明
本文为[hequnwang10]所创,转载请带上原文链接,感谢
https://blog.csdn.net/hequnwang10/article/details/124355525
边栏推荐
- matlab如何绘制已知公式的曲线图,Excel怎么绘制函数曲线图像?
- 2.Electron之HelloWorld
- Using quartz under. Net core - calendar of [6] jobs and triggers
- ClickHouse-SQL 操作
- On lambda powertools typescript
- JS, entries(), keys(), values(), some(), object Assign() traversal array usage
- Shell script -- shell programming specification and variables
- How does matlab draw the curve of known formula and how does excel draw the function curve image?
- flink 学习(十二)Allowed Lateness和 Side Output
- 01-初识sketch-sketch优势
猜你喜欢
If you start from zero according to the frame
Detailed explanation of C webpai route
01-初识sketch-sketch优势
XTask与Kotlin Coroutine的使用对比
[ES6] promise related (event loop, macro / micro task, promise, await / await)
Qt 修改UI没有生效
Future 用法详解
Using quartz under. Net core -- operation transfer parameters of [3] operation and trigger
1217_使用SCons生成目标文件
. net cross platform principle (Part I)
随机推荐
Flash project cross domain interception and DBM database learning [Baotou cultural and creative website development]
[C#] 彻底搞明白深拷贝
JS failed to change all variables and changed to the return method. Finally, the problem was solved
JVM类加载机制
Manually implement call, apply and bind functions
Shell - introduction, variables, and basic syntax
Shell-sort命令的使用
Come out after a thousand calls
Shell-入门、变量、以及基本的语法
[ES6] promise related (event loop, macro / micro task, promise, await / await)
Shell-awk命令的使用
基于51单片机红外无线通讯仿真
读《Software Engineering at Google》(15)
EF core in ASP Generate core priority database based on net entity model
Qt 修改UI没有生效
Net standard
C# Task. Delay and thread The difference between sleep
Error in v-on handler: "typeerror: cannot read property 'resetfields' of undefined"
1-4 configuration executable script of nodejs installation
C listens for WMI events