zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):堆类:第264题:丑数 II:编写一个程序,找出第 n 个丑数。 丑数就是质因数只包含 2, 3, 5 的正整数。

    题目:

    丑数 II:编写一个程序,找出第 n 个丑数。  丑数就是质因数只包含 2, 3, 5 的正整数。

    思路:

    使用最小堆来实现,借助哈希表保证了结果的唯一性。

    程序:

    import heapq
    class Solution:
        def nthUglyNumber(self, n: int) -> int:
            myHeap = []
            current_ugly = 1
            heapq.heappush(myHeap, current_ugly)
            findOut = set()
            findOut.add(current_ugly)
            elements = [2, 3, 5]
            index = 1
            while index <= n:
                current_ugly = heapq.heappop(myHeap)
                for element in elements:
                    new_ugly = current_ugly * element
                    if new_ugly in findOut:
                        continue
                    else:
                        findOut.add(new_ugly)
                        heapq.heappush(myHeap, new_ugly)
                index += 1
            return current_ugly
  • 相关阅读:
    数组
    2017.3.20for
    PHP基础2
    php基础1
    触发器
    SQL储存过程
    范式
    时间戳
    主键和外键
    15 大图轮播
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12899510.html
Copyright © 2011-2022 走看看