264. Ugly Number II(丑数 剑指offer 34)

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number, and n does not exceed 1690.

 

 

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        res = [1]
        p2 = p3 = p5 = 0
        while len(res) < n:
            mina = min(res[p2]*2,res[p3]*3,res[p5]*5)
            if mina == res[p2]*2:
                p2+=1
            # 防止2*3 重复的。p2++ p3也得++
            if mina == res[p3]*3:
                p3+=1
            if mina == res[p5]*5:
                p5+=1
            res.append(mina)
        print(res)
        return res[-1]

 

 

import heapq
#heapq = [1]
#heapq.heappush(heap, item)
#将 item 的值加入 heap 中,保持堆的不变性。

#heapq.heappop(heap)
#弹出并返回 heap 的最小的元素,保持堆的不变性。如果堆为空,抛出 IndexError 。使用 heap[0] ,可以只访问最小的元素而不弹出它。

#heapq.heappushpop(heap, item)
#将 item 放入堆中,然后弹出并返回 heap 的最小元素。该组合操作比先调用 heappush() 再调用 heappop() 运行起来更有效率。

#heapq.heapify(x)
#将list x 转换成堆,原地,线性时间内。

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        cur_set = set([1])
        q = [1]
        ugly = 1
        for i in range(0,n):
            ugly = heapq.heappop(q)
            for factor in [2,3,5]:
                if ugly*factor not in cur_set:
                    heapq.heappush(q,ugly*factor)
                    cur_set.add(ugly*factor)
        return ugly
                

 

 

posted @ 2018-03-11 12:53  乐乐章  阅读(159)  评论(0编辑  收藏  举报