第n个丑数
来源:互联网 发布:msn软件官方下载 编辑:程序博客网 时间:2024/05/22 04:47
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).
1到N的丑数为 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … ;
可以分成如下三组:只需要保证每次迭代的过程中选取最小的丑数(或者说是质因数),可以理解为后面的数字是前面的数组针对2,3,5的乘积。
C++可以AC的代码如下://求三个数的最小值 int min(int a, int b, int c){ int minNum = a > b ? b : a; return minNum > c ? c : minNum; } //求第N个丑数 int nthUglyNumber(int n) { int *ugly = new int[n]; memset(ugly, 0, sizeof(int) * n); ugly[0] = 1; int factor2 = 2, factor3 = 3, factor5 = 5; int index2, index3, index5; index2 = index3 = index5 = 0; for(int i=1; i<n; i++){ int minNum = min(factor2, factor3, factor5); ugly[i] = minNum; if(factor2 == minNum) factor2 = 2 * ugly[++index2]; if(factor3 == minNum) factor3 = 3 * ugly[++index3]; if(factor5 == minNum) factor5 = 5 * ugly[++index5]; } return ugly[n-1]; }
0 0
- 查找第N个丑数
- 找到第N个丑数
- 输出第n个丑数
- 返回第n个丑数
- 求第n个丑数
- 求第n个丑数
- 第n个丑数
- 找到第N个丑数
- 第n个丑数
- 输出第N个丑数
- 输出第N个丑数
- 第N个丑数生成算法
- java 求解第n个丑数
- 剑指off-求第n个丑数
- Ugly Number II 寻找第N个丑数
- [面试题12]第N个丑数
- C++求第N个丑数的值
- 笔试题:求第n个丑数
- Android Studio 运行时出现 finished with non-zero exit value 2
- 数字证书原理
- html iframe高度自适应
- maven项目部署到Repository(Nexus)
- 虚拟机在64位CentOS搭建lamp环境出现的一些报错以及解决方法
- 第n个丑数
- 数据结构之自建算法库——链栈
- Surrounded Regions
- 服务发现:Zookeeper vs etcd vs Consul
- 一个简单的算法---实现找出数组中一个数字出现次数最多的数字
- AngularJS $watch root scope variable for changes
- Java接口类只能声明静态属性
- 程序猿老张-上
- 如何在web.xml中加载外部多个xml文件