当前位置:网站首页>LeetCode-386 字典序排数
LeetCode-386 字典序排数
2022-04-22 13:47:00 【cc824恒】
题目给你一个整数 n ,按字典序返回范围 [1, n] 内所有整数。
你必须设计一个时间复杂度为 O(n) 且使用 O(1) 额外空间的算法。
示例 1:
输入:n = 13 输出:[1,10,11,12,13,2,3,4,5,6,7,8,9]
若不考虑时间复杂度和空间复杂度可以使用无脑操作
先把1-n的整数转为string类型,然后排序再加入到list中
代码:
class Solution {
public List<Integer> lexicalOrder(int n) {
String[] str = new String[n];
for(int i=0;i<n;i++)
str[i]=String.valueOf(i+1); //先将整数转为string类型
Arrays.sort(str); //按字典序排序
List<Integer> list = new ArrayList<>();
for(int i = 0;i<n;i++)
list.add(Integer.valueOf(str[i]));
return list;
}
}
若考虑到时间和空间复杂度
要使用 DFS (这个算法还没有掌握)
递归dfs
类似字典树的多阶树遍历,根节点为0,要被跳过,从第二层1-9开始
每一个节点有0-9 10个节点 如下图

class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> lexicalOrder(int n) {
for(int i=1;i<=9;i++)
dfs(i,n);
return list;
}
public void dfs(int cur,int limit){
if(cur > limit)
return;
list.add(cur);
for(int i=0;i<=9;i++)
dfs(cur*10+i,limit); //从左到右开始找
}
}
上述递归虽方便,但由于递归会使用栈,空间复杂度并不是O(1)所有改进一下
使用dfs迭代 符合空间复杂度O(1)
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> list = new ArrayList<>();
int number=1;
for(int i=0;i<n;i++){
list.add(number);
if(number*10<=n)
number=number*10;
else{
while(number%10==9||number+1>n) //到了每一个节点的末尾
number=number/10; //如果number=13 则下一个number=1
number++; //1+1=2 开始找2的子节点
}
}
return list;
}
}
版权声明
本文为[cc824恒]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_59887899/article/details/124246701
边栏推荐
猜你喜欢

C# 7.0 使用下划线忽略使用的变量

Communication principle of SPI protocol

【Flutter 专题】91 图解 Dart 单线程实现异步处理之 Future (二) #yyds干货盘点#

Trying to access array offset on value of type int

SixTool多功能多合一代挂助手系统源码
Sihao X6 safety configuration information exposure will be equipped with adaptive cruise

11 standard library of in-depth C language and program operation principle: in-depth understanding of standard IO (learning notes)

I changed the bug in the morning and was informed of being laid off in the afternoon

Genesis创意漫画之【稳定通证】

Fizz enterprise microservice Gateway - service choreography, offering a big killer to end the BFF layer
随机推荐
是什么让我节省了60%的编码时间?使用MBG
Xen thermal repair technology (basic understanding)
Socket的阻塞模式和非阻塞模式
High frequency interview questions of rapid tandem teaching and recruitment -- sorting algorithm and complexity
Is the account opening of Guoyuan futures company reliable? Is the transaction safe?
CDF全球调查:软件交付性能停滞不前
实现全链路重塑!从思维走向实践,数字化转型 IT 经营的成功路径
Apache SkyWalking 告警配置指南
数据库资源负载管理(下篇)
Citrix SQL数据如何进行多表联查
国元期货开户是否可靠?资金安全吗?
奥雅DAO社区质押挖矿dapp系统定制
Specify the parameter serialization component in the swagger interface document as newtonsoft Json
Redis Pipeline原来是这么用的
io_uring技术在分布式云原生数据库中的应用
上午在改BUG,下午就通知被裁了
Redis (IV) - string of common data types of redis
好物合集(1)
Originally, this is the correct posture for developers to open world book day!
What is the lifecycle of automated testing?