您的位置:首页 > 编程语言 > C语言/C++

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、解题如下:

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c++ 面试