leetcode 264 : Ugly Number II
2015-10-28 12:40
489 查看
1、原题如下:
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.
2、解题如下:
3、解题思路
本题采用一个buffer存放所有的ugly number,由于ugly number的特性我们能够知道,对于一个ugly number,它乘以2,3,5还是ugly number。所以,我们首先将第一个ugly number—1,放入buffer中,然后用2,3,5分别去乘,每次取出最小的数就是下一个ugly number,对于2,3,5来说,它们需要乘的次数不同,所以我们一定要保证buffer中的每一个数据都被2,3,5乘过,乘过的数一旦在比较中最小,也会再次加入进buffer中,这样我们就用i2,i3,i5来分别表示对应乘过的bufferid,避免遗漏,并保证每次找到的都是下一个最小的ugly number。
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.
2、解题如下:
class Solution { public: int nthUglyNumber(int n) { if(n<1) return 0; vector<int> buffer; int p2; int p3; int p5; int i2=0; int i3=0; int i5=0; int result=1; while(--n) { buffer.push_back(result); p2=2*buffer[i2]; p3=3*buffer[i3]; p5=5*buffer[i5]; result=min(p2,min(p3,p5)); if(result==p2) i2++; if(result==p3) i3++; if(result==p5) i5++; } return result; } };
3、解题思路
本题采用一个buffer存放所有的ugly number,由于ugly number的特性我们能够知道,对于一个ugly number,它乘以2,3,5还是ugly number。所以,我们首先将第一个ugly number—1,放入buffer中,然后用2,3,5分别去乘,每次取出最小的数就是下一个ugly number,对于2,3,5来说,它们需要乘的次数不同,所以我们一定要保证buffer中的每一个数据都被2,3,5乘过,乘过的数一旦在比较中最小,也会再次加入进buffer中,这样我们就用i2,i3,i5来分别表示对应乘过的bufferid,避免遗漏,并保证每次找到的都是下一个最小的ugly number。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 只有程序员看的懂的面试圣经|如何拿下编程面试
- 下一次技术面试时要问的 3 个重要问题
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- PHP程序员面试 切忌急功近利(更需要注重以后的发展)
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例