您的位置:首页 > 其它

leetcode之Ugly Number II

2015-12-11 16:56 423 查看
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).

题目描述:丑陋数的素因数仅仅包含2,3,5,求第n个丑陋数,1也被当作丑陋数。

思路:题目已经给出了具体的思路:可以将丑陋数拆分为下面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 。。。。

每一个子表都是有一个丑陋数乘 2, 3 ,5得到的,因此依次从上述3个子表中寻找最小的丑陋数添加到序列中即可,这相当于合并三个有序链表的操作。

代码如下:

class Solution {
public:
int nthUglyNumber(int n) {
vector<int>res(1,1);
int i2 = 0, i3 = 0, i5 = 0;
int l2, l3, l5;
while(res.size() < n){
l2 = res[i2] * 2;
l3 = res[i3] * 3;
l5 = res[i5] * 5;
int m = min(l2, min(l3, l5));
if(m == l2) i2++;
if(m == l3) i3++;
if(m == l5) i5++;
res.push_back(m);
}
return res.back();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: