4. 丑数 II

4. 丑数 II

中文English

设计一个算法,找出只含素因子235 的第 n 小的数。

符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12...

样例

样例 1:

输入:9
输出:10

样例 2:

输入:1
输出:1

挑战

要求时间复杂度为 O(nlogn) 或者 O(n)。

注意事项

我们可以认为 1 也是一个丑数。

方法一:列表 + 哈希表 + sorted排序

时间复杂度O(n*k),空间复杂度O(n*k) k = 3

class Solution:
    """
    @param {int} n an integer.
    @return {int} the nth prime number as description.
    """
    def nthUglyNumber(self, n):
        #哈希表 + 列表的思路
        seen = set([1])
        array = [1]

        for i in range(n):
            array = sorted(array)
            #每次取出最小的值去生成丑数,然后加进来
            val = array.pop(0)
            
            for j in [2,3,5]:
                new_ugly_num = j*val
                if new_ugly_num not in seen:
                    seen.add(new_ugly_num)
                    array.append(new_ugly_num)
        return val

方法二:堆 (最小堆) + 哈希表

时间复杂度:O(n*k)

空间复杂度:O(n*k)

每次都会自动从堆顶取出最小的元素,然后循环[2,3,5]生成丑数

import heapq

class Solution:
    """
    @param n: An integer
    @return: return a  integer as description.
    """
    def nthUglyNumber(self, n):
        # write your code here
        #堆 + 哈希表 
        
        #初始化堆里面的元素,然后往里面插值初始值1
        heap = []
        heapq.heappush(heap, 1)
        #初始化哈希表,用于记录之前已经生成过的丑数
        seen = set([1])
        
        #循环去堆顶取出丑数,然后根据当前丑数生成丑数
        for i in range(n):
            val = heapq.heappop(heap)#heappop每次会将堆顶的最小元素弹出来
            
            #根据取出的最小丑数生成丑数,存入堆里面
            for j in [2, 3, 5]:
                new_uply_num = val*j 
                if new_uply_num not in seen:
                    heapq.heappush(heap, new_uply_num)
                    seen.add(new_uply_num)
        
        return val
        
        
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13199356.html