Leetcode184: Ugly Number II
2015-12-05 23:54
387 查看
Write a program to find the
Ugly numbers are positive numbers whose prime factors only include
Note that
Hint:
The naive approach is to call
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).
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, 12is the sequence of the first
10ugly numbers.
Note that
1is typically treated as an ugly number.
Hint:
The naive approach is to call
isUglyfor 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).
class Solution { public: int nthUglyNumber(int n) { int *u = new int ; u[0] = 1; int f2=2, f3=3, f5=5; int i2=0, i3=0, i5=0; for(int i = 1; i < n; i++) { u[i] = min(f2,min(f3,f5)); if(f2 == u[i]) f2 = 2*u[++i2]; if(f3 == u[i]) f3 = 3*u[++i3]; if(f5 == u[i]) f5 = 5*u[++i5]; } return u[n-1]; } };
相关文章推荐
- selenium python (七)层级定位(二次定位)
- 牛客堂刷题之变态二分
- bundle update和bundle install的区别
- 欢迎使用CSDN-markdown编辑器
- java注册用户信息保存到txt中。
- 第二十三天-linux系统磁盘管理基础知识
- Linux系统文件名字体不同的颜色都代表什么
- avalon中ms-duplex
- wxPython环境搭建
- CPU 定位高
- 220-推桌子
- Add Two Numbers
- First Missing Positive
- 男生女生配
- 关于数组的练习题:
- Bootstrap历练实例:响应式标签页
- UESTC 1256 昊昊喜欢运动 n^2的预处理 or 前缀和
- 学习JS摘录
- HDUBC12.05题目
- sendredirect()和forward()的区别