[LeetCode][Python3] 313. Super Ugly Number
2019. 4. 13. 00:31 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/super-ugly-number/
My Solution :
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
ugly = [1]*n
idx = [0]*len(primes)
val = [1]*len(primes)
for i in range(1, n):
before = ugly[i-1]
candidate = float('INF')
for j, p in enumerate(primes):
if val[j] == before:
val[j] = p*ugly[idx[j]]
idx[j] += 1
candidate = min(candidate, val[j])
ugly[i] = candidate
return ugly[-1]
Comment :
위 방법은 지난번 문제의 DP 풀이를 활용한 것이고
2019/03/26 - [프로그래밍/LeetCode] - [LeetCode][Python3] 264. Ugly Number II
아래 방법은 heapq랑 set을 활용해 보았다.
My Solution 2 :
from heapq import heappush, heappop
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
queue = [1]
queue_set = set()
for _ in range(n-1):
num = heappop(queue)
for p in primes:
candidate = num*p
if candidate not in queue_set:
queue_set.add(candidate)
heappush(queue, candidate)
return queue[0]
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 54. Spiral Matrix (0) | 2019.04.18 |
---|---|
[LeetCode][Python3] 76. Minimum Window Substring (0) | 2019.04.16 |
[LeetCode][Python3] 84. Largest Rectangle in Histogram (0) | 2019.04.15 |
[LeetCode][Python3] 79. Word Search (0) | 2019.04.13 |
[LeetCode][Python3] 218. The Skyline Problem (0) | 2019.04.11 |
[LeetCode][Python3] 150. Evaluate Reverse Polish Notation (0) | 2019.04.10 |
[LeetCode][Python3] 33. Search in Rotated Sorted Array (0) | 2019.04.10 |
[LeetCode][Python3] 227. Basic Calculator II (0) | 2019.04.09 |
최근에 달린 댓글 최근에 달린 댓글