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

相关推荐
科雷软件测试21 小时前
Python中itertools.product:快速生成笛卡尔积
开发语言·python
OOJO1 天前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
别或许1 天前
1、高数----函数极限与连续(知识总结)
算法
派大星~课堂1 天前
【力扣-142. 环形链表2 ✨】Python笔记
python·leetcode·链表
田梓燊1 天前
code 560
数据结构·算法·哈希算法
Thomas.Sir1 天前
第一章:Agent智能体开发实战之【初步认识 LlamaIndex:从入门到实操】
人工智能·python·ai·检索增强·llama·llamaindex
笨笨饿1 天前
29_Z变换在工程中的实际意义
c语言·开发语言·人工智能·单片机·mcu·算法·机器人
kobesdu1 天前
综合强度信息的激光雷达去拖尾算法解析和源码实现
算法·机器人·ros·slam·激光雷达
weixin_413063211 天前
记录 MeshFlow-Online-Video-Stabilization 在线稳像
算法·meshflow·实时防抖
ZTL-NPU1 天前
Jetbrains开发ros
ide·python·pycharm·编辑器·ros·clion