leetcode Super Ugly Number
Write a program to find the nth super ugly number.
Super ugly numbers are positive numbers whose all prime factors are in the given prime list
primes
of sizek
. For example,[1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32]
is the sequence of the first 12 super ugly numbers givenprimes
=[2, 7, 13, 19]
of size 4.Note: (1)
1
is a super ugly number for any givenprimes
. (2) The given numbers inprimes
are in ascending order. (3) 0 <k
≤ 100, 0 <n
≤ 106, 0 <primes[i]
< 1000.
题目地址: leetcode Super Ugly Number
题意:
给定因子Primes , 让你求第n个super ugly number。
super ugly number定义为:整数,且因子全部都在primes中。 注意1为特殊的super ugly number。
思路:
和 leetcode Ugly Number II 思路一样,要使得super ugly number 不漏掉,那么用每个因子去乘第一个,当前因子乘积是最小后,乘以下一个.....以此类推。
C++
1 | struct Node { |
Java
1 | class Solution { |
Python 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
ans = [1] * n
q = [[prime, 0, prime] for prime in primes]
heapq.heapify(q)
for i in range(1, n):
cur = heapq.heappop(q)
ans[i] = cur[0]
while q and q[0][0] == ans[i]:
t = heapq.heappop(q)
t[1] += 1
t[0] = ans[t[1]] * t[2]
heapq.heappush(q, t)
cur[1] += 1
cur[0] = ans[cur[1]] * cur[2]
heapq.heappush(q, cur)
return ans[n - 1]