Ugly Number II -- leetcode

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:

  1. 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.
  2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
  3. 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.
  4. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).

算法一,DP逐个生成ugly numbers

1. ugly number初始为1

2. 每次循环生成一个新的次大ugly number

即从小到大生成ugly number。

3. 从已经生成的ugly number中,挑选一个,使其*2, 或者*3, *5,得到下一个ugly number。

即 = min(x*2, min(y*3, z*5))  x, y, z为已经生成的ugly number

class Solution {
public:
    int nthUglyNumber(int n) {
        vector uglys(n, 1);
        int id2 = 0, id3 = 0, id5 = 0;
        for (int i=1; i


算法一开始分配了n个存储空间,用来存储n个ugly number。

但在生成新的ugly number时,前面的逐渐开始不需要了。

将vector,改作list,这样,可以把前面不再需要的ugly number逐渐删除掉,以节省空间。


class Solution {
public:
    int nthUglyNumber(int n) {
        list uglys;
        uglys.push_back(1);
        auto iter2 = uglys.begin();
        auto iter3 = uglys.begin();
        auto iter5 = uglys.begin();
        for (int i=1; i


算法二,显示归并

和算法一思路差不多。算法一,隐式有三个队列,并作归并。

此处,显示的设置三个队列。

1. 每当求得一个新的ugly number,将期*2, *3, *5,并分别送入三个队列。

2. 对这个三队列作归并,求出一个新的ugly number。

3. 重复步骤1,2

class Solution {
public:
    int nthUglyNumber(int n) {
        int ans = 1;
        --n;
        queue L2, L3, L5;
        while (n--) {
            L2.push(ans * 2);
            L3.push(ans * 3);
            L5.push(ans * 5);
            while (L2.front() <= ans) L2.pop();
            while (L3.front() <= ans) L3.pop();
            while (L5.front() <= ans) L5.pop();
            ans = min(L2.front(), min(L3.front(), L5.front()));
        }
        return ans;
    }
};



你可能感兴趣的:(面试题,leetcode,prime,number,动态归划,归并)