首页 > 编程语言 > 详细

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

时间:2020-05-16 12:11:03      阅读:182      评论:0      收藏:0      [点我收藏+]

题目:

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

  

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

原文:https://www.cnblogs.com/zhuozige/p/12899510.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!