丑数 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

相关推荐
PiKaMouse.10 分钟前
navigation2-humble从零带读笔记第一篇:nav2_core
c++·算法·机器人
木井巳16 分钟前
【递归算法】子集
java·算法·leetcode·决策树·深度优先
lightqjx42 分钟前
【算法】二分算法
c++·算法·leetcode·二分算法·二分模板
Zzzz_my1 小时前
正则表达式(RE)
pytorch·python·正则表达式
天天鸭1 小时前
前端仔写了个 AI Agent,才发现大模型只干了 10% 的活
前端·python·ai编程
Wave8452 小时前
数据结构—树
数据结构
ic爱吃蓝莓2 小时前
数据结构 | HashMap原理
数据结构·学习·算法·链表·哈希算法
add45a2 小时前
C++编译期数据结构
开发语言·c++·算法
setmoon2142 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
灰色小旋风2 小时前
力扣21 合并两个有序链表(C++)
c++·leetcode·链表