leetcode -- Super Ugly Number -- 跟ugly number系列一起复习

https://leetcode.com/problems/super-ugly-number/
https://leetcode.com/problems/ugly-number-ii/

思路1 TLE

像ugly number II 的思路, 过不了大case, TLE.因为每次都要生成一个minlist,但其实每次这个minlist只更新了一个值而已。所以我们维护一个min heap是最好的。用heapq

class Solution(object):
    def nthSuperUglyNumber(self, n, primes):
        """ :type n: int :type primes: List[int] :rtype: int """

        length = len(primes)
        idx = [0] * length
        ans = [1]
        while len(ans) < n:
            minlist = [primes[i]*ans[idx[i]] for i in xrange(len(idx))]
            umin = min(minlist)
            min_idx = minlist.index(umin)
            idx[min_idx] += 1
            if umin != ans[-1]:
                ans.append(umin)
            #print (minlist, min_idx, ans)


        return ans[-1]   

思路1改进,用heapq

import heapq
class Solution(object):
    def nthSuperUglyNumber(self, n, primes):
        """ :type n: int :type primes: List[int] :rtype: int """

        length = len(primes)
        idx = [0] * length
        ans = [1]
        minlist = [(primes[i]*ans[idx[i]], i) for i in xrange(len(idx))] #[(val, idx),(),...],这里把val和idx算作tuple算进去。
        heapq.heapify(minlist)
        while len(ans) < n:
            (umin, min_idx) = heapq.heappop(minlist)
            idx[min_idx] += 1
            if umin != ans[-1]:
                ans.append(umin)
            heapq.heappush(minlist, (primes[min_idx]*ans[idx[min_idx]], min_idx))


        return ans[-1]    

要看http://blog.csdn.net/xyqzki/article/details/50516439, 关于heapq运用。

Ugly Number

http://blog.csdn.net/xyqzki/article/details/50121225

Ugly Number II

http://blog.csdn.net/xyqzki/article/details/50127749

这里的思路就是给定一个质数集合,不断的生成下一个最小的质数

参考
http://bookshadow.com/weblog/2015/12/03/leetcode-super-ugly-number/
http://zhangxi-lam.github.io/2015/12/04/4_%E6%AF%8F%E6%97%A5%E4%B8%80%E5%88%B7-Super-Ugly-Number/

你可能感兴趣的:(leetcode -- Super Ugly Number -- 跟ugly number系列一起复习)