๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/LeetCode

๐Ÿ’ฏ Daily LeetCode Challenge Day_04 - Ugly Number II

by HaningYa 2020. 7. 6.
728x90

 

 

Account Login - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


๋ฌธ์ œ

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. 1 is typically treated as an ugly number.
  2. 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

๋Œ“๊ธ€