[LeetCode][Python3] 264. Ugly Number II
2019. 3. 26. 01:29 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/ugly-number-ii/
My Solution :
class Solution:
def nthUglyNumber(self, n: int) -> int:
ugly = [1]*n
p2 = p3 = p5 = 0
for i in range(1, n):
u2, u3, u5 = 2*ugly[p2], 3*ugly[p3], 5*ugly[p5]
ugly[i] = min(u2, u3, u5)
if ugly[i] == u2:
p2 += 1
if ugly[i] == u3:
p3 += 1
if ugly[i] == u5:
p5 += 1
return ugly[-1]
Comment :
위 DP가 최적의 접근법으로 보인다. 아래는 비슷한 개념을 queue를 활용하여 접근한 것.
My Solution 2:
from collections import deque
class Solution:
def nthUglyNumber(self, n: int) -> int:
ugly = 1
q2, q3, q5 = [deque() for _ in range(3)]
for _ in range(n-1):
q2.append(ugly*2)
q3.append(ugly*3)
q5.append(ugly*5)
ugly = min(q2[0], q3[0], q5[0])
for q in (q2, q3, q5):
if q[0] == ugly:
q.popleft()
return ugly
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 315. Count of Smaller Numbers After Self (0) | 2019.03.28 |
---|---|
[LeetCode][Python3] 395. Longest Substring with At Least K Repeating Characters (0) | 2019.03.28 |
[LeetCode][Python3] 73. Set Matrix Zeroes (0) | 2019.03.27 |
[LeetCode][Python3] 329. Longest Increasing Path in a Matrix (0) | 2019.03.27 |
[LeetCode][Python3] 334. Increasing Triplet Subsequence (0) | 2019.03.25 |
[LeetCode][Python3] 297. Serialize and Deserialize Binary Tree (0) | 2019.03.25 |
[LeetCode][Python3] 105. Construct Binary Tree from Preorder and Inorder Traversal (0) | 2019.03.24 |
[LeetCode][Python3] 131. Palindrome Partitioning (0) | 2019.03.23 |
최근에 달린 댓글 최근에 달린 댓글