【LeetCode】Ugly Number II 解题报告
2015-10-18 21:40
483 查看
Ugly Number II
[LeetCode]https://leetcode.com/problems/ugly-number-ii/
Total Accepted: 12227 Total Submissions: 54870 Difficulty: Medium
Question
Write a program to find the n-th ugly number.Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Examples
For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.Note that 1 is typically treated as an ugly number.
Ways
方法一
最简单的方法就是遍历的方法,直接判断每个数是不是丑数,如果是就加入list中,这就是方法一。但是这个方法效率太低,提交的时候连续三次都超出时间限制了。本地运行还是可以的。迫于无奈,必须提高效率。
方法二
所有的ugly number都是由1开始,乘以2/3/5生成的。只要将这些生成的数排序即可获得,自动排序可以使用set
这样每次取出的第一个元素就是最小元素,由此再继续生成新的ugly number.
可以分成如下三组:
(1) 1×2, 2×2, 3×2, 4×2, 5×2, …
(2) 1×3, 2×3, 3×3, 4×3, 5×3, …
(3) 1×5, 2×5, 3×5, 4×5, 5×5, …
使每个组已经用过的数字删除掉,这样列表中只有一个元素,获取三个组的最小值之后就计算下一个丑数。
[code]public static int nthUglyNumber2(int n) { List<Integer> num2List = new ArrayList<Integer>(); List<Integer> num3List = new ArrayList<Integer>(); List<Integer> num5List = new ArrayList<Integer>(); num2List.add(1); num3List.add(1); num5List.add(1); int test = 0; for (int j = 0; j < n; j++) { //最小元素 test = Math.min(Math.min(num2List.get(0), num3List.get(0)), num5List.get(0)); //让列表中一直只有一个元素 if (num2List.get(0) == test) num2List.remove(0); if (num3List.get(0) == test) num3List.remove(0); if (num5List.get(0) == test) num5List.remove(0); num2List.add(2 * test); num3List.add(3 * test); num5List.add(5 * test); } return test; }
Solution
托管在我的GitHub上:https://github.com/fuxuemingzhu/UglyNumber2
Captures
测试结果截图:Reference
/article/3634588.htmlhttp://blog.csdn.net/xudli/article/details/47903959
Date
2015/10/18 20:57:01相关文章推荐
- Spring boot mongo pom
- android 45 通知
- js实现分页的几个源码,看完基本就懂了
- iOS GDataXMLNode 解析XML DOM方式 总结
- HashMap实现原理
- linux下对mysql的数据库进行定时备份
- 必须熟练英语
- 第三次作业 计算器
- IOS圆形头像的设置
- c语言中的变量声明
- 归并排序
- 周日
- sharepoint 2016 学习系列篇(13)-自定义列表应用篇-(2)添加字段栏
- Ruby学习-Ruby类的使用
- ARM应用程序调试
- java实现压缩、解压缩的常见问题Memo
- 计算机C语言的介绍
- PIC单片机DS18B20温度报警程序及仿真
- MongoProperties
- [Codechef October Challenge 2014]刷漆