leetcode之Ugly Number II
2015-12-11 16:56
423 查看
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 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.
Hint:
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
题目描述:丑陋数的素因数仅仅包含2,3,5,求第n个丑陋数,1也被当作丑陋数。
思路:题目已经给出了具体的思路:可以将丑陋数拆分为下面3个子表:
(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 。。。。
每一个子表都是有一个丑陋数乘 2, 3 ,5得到的,因此依次从上述3个子表中寻找最小的丑陋数添加到序列中即可,这相当于合并三个有序链表的操作。
代码如下:
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 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.
Hint:
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
题目描述:丑陋数的素因数仅仅包含2,3,5,求第n个丑陋数,1也被当作丑陋数。
思路:题目已经给出了具体的思路:可以将丑陋数拆分为下面3个子表:
(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 。。。。
每一个子表都是有一个丑陋数乘 2, 3 ,5得到的,因此依次从上述3个子表中寻找最小的丑陋数添加到序列中即可,这相当于合并三个有序链表的操作。
代码如下:
class Solution { public: int nthUglyNumber(int n) { vector<int>res(1,1); int i2 = 0, i3 = 0, i5 = 0; int l2, l3, l5; while(res.size() < n){ l2 = res[i2] * 2; l3 = res[i3] * 3; l5 = res[i5] * 5; int m = min(l2, min(l3, l5)); if(m == l2) i2++; if(m == l3) i3++; if(m == l5) i5++; res.push_back(m); } return res.back(); } };
相关文章推荐
- android x264 编码 h264 demo
- 使用dwr时动态生成table的一个小技巧
- 统计字符串中的单词数目
- SVM学习笔记(一)
- 内核模块加载
- Nginx+Keepalived实现站点高可用
- adb adb devices offline 快速解决的办法,android adb 连接失败
- Communications link failure
- 输入文本校验
- 微信JS-SDK接口操作
- MD5 、AES加密、BASE64编码
- ListView 点击某一项换背景图片
- RequireJS进阶(三) 转
- Log4J日志配置详解
- scanf函数详解
- 5.7、安全与部署
- PHP 对多个数组合并去重&以及数组键值的翻转
- 多种形态的圆形进度条CircleProgress
- 配置NFS
- DD测试磁盘读写速度