[Leetcode] Ugly Number II
2016-04-06 15:20
274 查看
题目描述:
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).
题目大意:
编写程序寻找第n个“丑陋数” ugly number丑陋数是指只包含质因子2, 3, 5的正整数。例如,1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前10个丑陋数。
注意,数字1也被视为丑陋数
提示:
朴素的方法是对每一个数字重复调用isUgly方法,直到找到第n个为止。但是大部分数字都不是丑陋的。尝试寻找只生成丑陋数的方法
丑陋数必须由一个较小的丑陋数乘以2,3或者5得到
解决问题的关键是维护丑陋数的顺序。尝试一个类似于合并3个有序列表L1,L2与L3的方法
假设你当前计算出了第k个丑陋数Uk。则Uk+1一定是Min(L1 *
2, L2 * 3, L3 * 5)
解题思路:
参考:http://www.geeksforgeeks.org/ugly-numbers/丑陋数序列可以拆分为下面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, …
我们可以发现每一个子列表都是丑陋数本身(1, 2, 3, 4, 5, …) 乘以 2, 3, 5
接下来我们使用与归并排序相似的合并方法,从3个子列表中获取丑陋数。每一步我们从中选出最小的一个,然后向后移动一步。
C++代码:
<span style="font-size:14px;">class Solution {
public:
int nthUglyNumber(int n) {
vector<int> ans(1,1);
int ind2=0,ind3=0,ind5=0;
int a2,a3,a5;
for(int i=1;i<n;i++){
a2=ans[ind2]*2;
a3=ans[ind3]*3;
a5=ans[ind5]*5;
if(a2<=a3&&a2<=a5){
ans.push_back(a2);
ind2++;
if(a2==a3) ind3++;
if(a2==a5) ind5++;
}
else if(a2>=a3&&a3<=a5){
ans.push_back(a3);
ind3++;
if(a2==a3) ind2++;
if(a3==a5) ind5++;
}
else if(a5<=a3&&a5<=a2){
ans.push_back(a5);
ind5++;
if(a5==a3) ind3++;
if(a2==a5) ind2++;
}
}
return ans.back();
}
};</span>
Python代码:
class Solution: # @param {integer} n # @return {integer} def nthUglyNumber(self, n): q = [1] i2 = i3 = i5 = 0 while len(q) < n: m2, m3, m5 = q[i2] * 2, q[i3] * 3, q[i5] * 5 m = min(m2, m3, m5) if m == m2: i2 += 1 if m == m3: i3 += 1 if m == m5: i5 += 1 q += m, return q[-1]
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- 关于指针的一些事情
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例