★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-gnozurvl-ko.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Write a program to find the nth
super ugly number.git
Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes
of size k
.github
Example:微信
Input: n = 12, = Output: 32 Explanation: is the sequence of the first 12 super ugly numbers given = of size 4.primes[2,7,13,19][1,2,4,7,8,13,14,16,19,26,28,32]primes[2,7,13,19]
Note:app
1
is a super ugly number for any given primes
.primes
are in ascending order.k
≤ 100, 0 < n
≤ 106, 0 < primes[i]
< 1000.編寫一段程序來查找第 n
個超級醜數。spa
超級醜數是指其全部質因數都是長度爲 k
的質數列表 primes
中的正整數。code
示例:htm
輸入: n = 12, = 輸出: 32 解釋: 給定長度爲 4 的質數列表 primes = [2,7,13,19],前 12 個超級醜數序列爲:[1,2,4,7,8,13,14,16,19,26,28,32] 。primes[2,7,13,19]
說明:blog
1
是任何給定 primes
的超級醜數。primes
中的數字以升序排列。k
≤ 100, 0 < n
≤ 106, 0 < primes[i]
< 1000 。n
個超級醜數確保在 32 位有符整數範圍內。116 msget
1 class Solution { 2 func nthSuperUglyNumber(_ n: Int, _ primes: [Int]) -> Int { 3 let count = primes.count 4 5 var index = Array(repeatElement(0, count: count)) 6 var value = primes 7 var temp = 0 8 9 var ugly = [1] 10 for _ in 0..<n - 1 { 11 temp = Int.max 12 for j in 0..<count { 13 temp = min(temp, value[j]) 14 } 15 ugly.append(temp) 16 for j in 0..<count { 17 if temp == value[j] { 18 index[j] += 1 19 value[j] = ugly[index[j]] * primes[j] 20 } 21 } 22 } 23 return ugly[n - 1] 24 } 25 }
556ms
1 class Solution { 2 func nthSuperUglyNumber(_ n: Int, _ primes: [Int]) -> Int { 3 var res = [1] 4 var c = Array(repeating: 0, count: primes.count) 5 6 for _ in 0 ..< n-1 { 7 var comp = [Int]() 8 for i in 0 ..< primes.count { 9 comp.append(res[c[i]] * primes[i]) 10 } 11 12 let minP = comp.min()! 13 res.append(minP) 14 15 for j in 0 ..< comp.count where comp[j] == minP { 16 c[j] += 1 17 } 18 } 19 20 return res.last! 21 } 22 }