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

相关推荐
Hello.Reader1 天前
PyFlink 向量化 UDF(Vectorized UDF)Arrow 批传输原理、pandas 标量/聚合函数、配置与内存陷阱、五种写法一网打尽
python·flink·pandas
hweiyu001 天前
二分图匹配算法:匈牙利算法
算法
IAR Systems1 天前
在IAR Embedded Workbench for Renesas RH850中实现ROPI
linux·运维·算法
曲幽1 天前
FastAPI + SQLite:从基础CRUD到安全并发的实战指南
python·sqlite·fastapi·web·jwt·form·sqlalchemy·oauth2
用户4303510250681 天前
Python 中除 Ecception 外的三类系统异常
python
搂着猫睡的小鱼鱼1 天前
基于Python的淘宝评论爬虫
开发语言·爬虫·python
小途软件1 天前
基于深度学习的人脸属性增强器
java·人工智能·pytorch·python·深度学习·语言模型
ai_top_trends1 天前
AI 生成工作计划 PPT 是否适合年初规划与年度汇报
人工智能·python·powerpoint
一个不知名程序员www1 天前
算法学习入门--- set与map(C++)
c++·算法
POLITE31 天前
Leetcode 142.环形链表 II JavaScript (Day 10)
javascript·leetcode·链表