LeetCode笔记:386. Lexicographical Numbers
来源:互联网 发布:小公司网络组建 编辑:程序博客网 时间:2024/05/29 02:04
问题:
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.
思路:
给出一个整数n,返回 1 到 n 的词典顺序。
比如,给出13,返回 [1,10,11,12,13,2,3,4,5,6,7,8,9]。
请优化你的代码来使用更少的时间和空间。输入范围会达到5000000。
思路:
问题的关键在于理清“词典顺序”是什么样的。
词典顺序就是10比2靠前,101比11靠前,110比11靠后,你可以简单的尝试一下把数字都转换成字符串数组,然后对字符串数组进行 Arrays.sort(),就会得到字符串下词典顺序的数字。但是这个方法因为用了排序,是会超时的。
所以我们的做法大致顺序如下:
1、如果一个数乘以十以后没有超过n,那它后面紧挨着的应该是它的十倍,比如1,10,100。
2、如果不满足1,那就应该是直接加一,比如n为13的时候,前一个数为12,120超过了n,那接着的应该是13。但是这里要注意如果前一个数的个位已经是9或者是它就是n了,那就不能加一了,比如 n = 25,前一个数为19,下一个数应该为2而不是19+1=20。25的下一个也没有26了。
3、如果不满足2,比如19后面应该接2而不是20,这时候应该将19除以10再加一,比如n=500,399的下一个应该是4,那就是除以十,个位还是9,继续除以10,得到3,加一得到4。
将上面的过程整理成代码就可以了,循环的次数就是n,也就是总个数。
代码(Java):
public class Solution { public List<Integer> lexicalOrder(int n) { List<Integer> res = new ArrayList<Integer>(); int cur = 1; for (int i = 1; i <= n; i++) { res.add(cur); if (cur * 10 <= n) { cur = cur * 10; } else if (cur % 10 != 9 && cur + 1 <= n) { cur++; } else { while ((cur / 10) % 10 == 9) { cur = cur / 10; } cur = cur / 10 + 1; } } return res; }}
合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_
- LeetCode笔记:386. Lexicographical Numbers
- [leetcode] 386. Lexicographical Numbers
- [leetcode]386. Lexicographical Numbers
- 【Leetcode】386. Lexicographical Numbers
- [Leetcode]386. Lexicographical Numbers
- LeetCode 386. Lexicographical Numbers
- 【LeetCode】 386. Lexicographical Numbers
- [leetcode]386. Lexicographical Numbers
- LeetCode 386. Lexicographical Numbers
- LeetCode 386. Lexicographical Numbers
- [LeetCode]386. Lexicographical Numbers
- leetcode 386. Lexicographical Numbers
- LeetCode—386. Lexicographical Numbers
- LeetCode—386. Lexicographical Numbers
- 【LeetCode题解】386. Lexicographical Numbers
- leetcode 386. Lexicographical Numbers 解题报告
- LeetCode-386. Lexicographical Numbers-思路详解-C++
- leetcode oj java 386. Lexicographical Numbers
- bzoj 4698: Sdoi2008 Sandy的卡片 (后缀数组+二分)
- ImageLoadAsyncTask--MainActivity
- emmc 通过reset controller 来reset emmc host
- 说说显示器接口那点事!VGA、DVI、HDMI,DP
- 【LeetCode】 237. Delete Node in a Linked List C语言
- LeetCode笔记:386. Lexicographical Numbers
- CentOS 7 安装GitLab
- Linux下打补丁
- Java程序员必须掌握的8大排序算法
- Java虚拟机类加载机制
- 每天一个Linux命令(50):route
- 轻量级操作系统FreeRTOS的内存管理机制(一)
- IP地址的CString型和DWORD型转换
- 青涩的时光写给未来的自己——程序员不能Low