丑数 II(LeetCode)

题目

给你一个整数 n ,请你找出并返回第 n丑数

丑数 就是质因子只包含 235 的正整数。

解题

python 复制代码
def nthUglyNumber(n: int) -> int:
    # 初始化 dp 数组
    dp = [0] * n
    dp[0] = 1

    # 初始化三个指针
    p2 = p3 = p5 = 0

    for i in range(1, n):
        # 计算当前三个候选丑数
        next_ugly = min(dp[p2] * 2, dp[p3] * 3, dp[p5] * 5)

        # 更新 dp 数组
        dp[i] = next_ugly

        # 移动指针
        if next_ugly == dp[p2] * 2:
            p2 += 1
        if next_ugly == dp[p3] * 3:
            p3 += 1
        if next_ugly == dp[p5] * 5:
            p5 += 1

    return dp[n - 1]


# 测试代码
n = 10
print(f"The {n}th ugly number is: {nthUglyNumber(n)}")

The 10th ugly number is: 12

相关推荐
xlp666hub10 分钟前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
有意义2 小时前
深度拆解分割等和子集:一维DP数组与倒序遍历的本质
前端·算法·面试
xlp666hub3 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
用户726876103374 小时前
解放双手的健身助手:基于 Rokid AR 眼镜的运动计时应用
算法
Wect4 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·typescript
明月_清风6 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风6 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
xlp666hub20 小时前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
程序员小崔日记1 天前
大三备战考研 + 找实习:我整理了 20 道必会的时间复杂度题(建议收藏)
算法·408·计算机考研