728x90
๋ฌธ์
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example:
Input: n = 10 Output: 12 Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:
- 1 is typically treated as an ugly number.
- n does not exceed 1690.
n ์ด 1690 ๊น์ง ๋๋ ์ผ์ผํ ์์๋ฅผ ์ฐพ์๊ฐ๋ฉฐ n๋ฒ์งธ ์๋ฅผ ์ฐพ๋ ๊ฒ์ ๋ถ๊ฐ๋ฅ ํ๋ค.
2,3,5 ๋ง์ผ๋ก ์ด๋ฃจ์ด์ง ์๋ฅผ n๋ฒ์งธ ๊น์ง ๋ง๋๋๊ฒ Valid ํ Solution์ด๋ค.
idea ๋ ์ด๋ ๋ค.
์ ์ผ ์์ valid ์ซ์ 1์ ๋ฃ์ ๋ค์
[1]
2,3,5์ ๋ฐฐ์์ค ๊ฐ์ฅ ์์ ์๋ฅผ ์ง์ด๋ฃ๋๋ค.(2,3,5)
[1,2]
๋ค์ ๋จ๊ณ๋ (4,3,5) ์ด๋ฏ๋ก 3์ด append ๋๋ค.
[1,2,3,4]
์ฌํผ ํ๋ก ๋ํ๋ด๋ฉด ์ด๋ ๋ค.
m2 | m3 | m5 | i | j | k | min | list |
2 | 3 | 5 | 0 | 0 | 0 | 2 | [1,2] |
4 | 3 | 5 | 1 | 0 | 0 | 3 | [1,2,3] |
4 | 6 | 5 | 1 | 1 | 0 | 4 | [1,2,3,4] |
8 | 6 | 5 | 2 | 1 | 1 | 5 | [1,2,3,4,5] |
8 | 6 | 10 | 2 | 1 | 2 | 6 | [1,2,3,4,5,6] |
์ดํ ์๋ต |
class Solution {
func nthUglyNumber(_ n: Int) -> Int {
if n <= 0 {
return 0
}
var list : [Int] = []
list.append(1)
var i = 0
var j = 0
var k = 0
while list.count < n {
var m2 = list[i]*2
var m3 = list[j]*3
var m5 = list[k]*5
var minNum = min(m2, min(m3,m5))
list.append(minNum)
if (minNum==m2) {i+=1}
if (minNum==m3) {j+=1}
if (minNum==m5) {k+=1}
// print(list)
}
return list[list.count-1]
}
}
728x90
'Algorithm > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฏ Daily LeetCode Challenge Day_06 - Plus One (0) | 2020.07.07 |
---|---|
๐ฏ Daily LeetCode Challenge Day_05 - Hamming Distance (2) | 2020.07.06 |
๐ฏ Daily LeetCode Challenge Day_03 - Prison Cells After N Days (0) | 2020.07.03 |
๐ฏ Daily LeetCode Challenge Day_02 - Binary Tree Level Order Traversal II (0) | 2020.07.03 |
๐ฏ Daily LeetCode Challenge Day_01 - Arranging Coins (0) | 2020.07.01 |
๋๊ธ