标签:
Write a program to find the nth super ugly number.
Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes
of size k
. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32]
is the sequence of the first 12 super ugly numbers given primes
= [2, 7, 13, 19]
of size 4.
Note:
(1) 1
is a super ugly number for any given primes
.
(2) The given numbers in primes
are in ascending order.
(3) 0 < k
≤ 100, 0 < n
≤ 106, 0 < primes[i]
< 1000.
思路:解法和ugly number II一样。复杂度O(kn)。
这个算法有一个改进的地方,min函数可以用最小堆来实现。这样复杂度是O(log(k)n)。
1 class Solution { 2 public: 3 int min(vector<int>& primes, vector<int>& pointers, vector<int>& superUglyNumber) { 4 int res = INT_MAX; 5 for (int i = 0, n = primes.size(); i < n; i++) 6 if (res > superUglyNumber[pointers[i]] * primes[i]) 7 res = superUglyNumber[pointers[i]] * primes[i]; 8 for (int i = 0, n = primes.size(); i < n; i++) 9 if (res == superUglyNumber[pointers[i]] * primes[i]) 10 pointers[i]++; 11 return res; 12 } 13 int nthSuperUglyNumber(int n, vector<int>& primes) { 14 vector<int> superUglyNumber; 15 superUglyNumber.push_back(1); 16 vector<int> pointers(primes.size()); 17 for (int i = 1; i < n; i++) 18 superUglyNumber.push_back(min(primes, pointers, superUglyNumber)); 19 return superUglyNumber.back(); 20 } 21 };
标签:
原文地址:http://www.cnblogs.com/fenshen371/p/5783347.html