Leetcode 264. Ugly Number II

Leetcode 264. Ugly Number II

@(LeetCode)[LeetCode | Algorithm | DP]

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

Example:

Input: n = 10
Output: 12

Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Original problem is HERE.


Solution #1

Time: O(n) O ( n )
Space: O(n) O ( n )

一开始的想法是:从1开始遍历,判断每一个数是否是ugly number,最终找到第n个ugly number。看似是线性时间,实际上并不是,因为到后面相邻两个ugly number之间的距离会非常大。当n较大时,找到下一个ugly number可能会花费很多时间。所以这个想法行不通

另一个想法就是:自动生成ugly number。直接想到的就是DP,dp[i]就表示第i个ugly number这个想法是可行的,难点在于如何依次生成每一个ugly number。每一个ugly number都可以生成3个不同的ugly numbers,也即dp[i] * 2dp[i] * 3dp[i] * 5,我们可以设置3个指针依次指向乘2,乘3,乘5的index。下一个dp[i+1],就是取3个中最小的,并将对应的指针往前移一位。

The basic idea is generating ugly numbers by using dynamic programming, dp[i] represents the i-th ugly number. A critical point here is that how can we generate those ugly numbers in order, otherwise we cannot find the n-th ugly number. Every ugly number can generate 3 different ugly numbers, i.e., dp[i] * 2, dp[i] * 3, dp[i] * 5. Thereby, we need the help of 3 pointers to “sort” them. Each pointer points to the multiplier of 2, 3 and 5. During each round, we find

dp[i] = min(dp[t2] * 2, min(dp[t3] * 3, dp[t5] * 5));

and move the corresponding pointer 1-position forward.

class Solution {
public:
    int nthUglyNumber(int n) {
        int t2 = 0, t3 = 0, t5 = 0;
        vector<int> dp(n);
        dp[0] = 1;

        for(int i = 1; i < n; i++){
            dp[i] = min(dp[t2] * 2, min(dp[t3] * 3, dp[t5] * 5));

            if(dp[i] == dp[t2] * 2)
                t2++;
            if(dp[i] == dp[t3] * 3)
                t3++;
            if(dp[i] == dp[t5] * 5)
                t5++;
        }

        return dp.back();
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值