Ugly Number II
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that 1
is typically treated as an ugly number, and n does not exceed 1690.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
解析:
代码:
class Solution {
public:
int nthUglyNumber(int n) {
vector<int>index(3,0);
vector<int>ugly(n,INT_MAX);
if (n==1) return 1;
ugly[0]=1;
vector<int>base(3,0);
base[0]=2;
base[1]=3;
base[2]=5;
for (int i=1; i<n; i++)
{
for (int j=0; j<3; j++)
{
ugly[i]=min(ugly[i],ugly[index[j]]*base[j]);
}
for (int j=0; j<3; j++)
{
while (ugly[index[j]]*base[j]<=ugly[i])
index[j]++;
}
}
return ugly[n-1];
}
};
Super Ugly Number
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.
(4) The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
ugly[i]为第i个丑数,把得到的第一个乘以2后大于M的结果记为M2,同样把已有的每个丑数乘以3和5,得到第一个大于M的结果即为M3和M5,那么下一个丑数为M2,M3,M5这三个数中的最小者,因为所有丑数都是按顺序存放在数组中的,对乘以2而言,肯定存在一个某个丑数T2,排在他之前的每个丑数乘以2得到的结果都会小于已有的最大丑数,在他之后的每一个丑数乘以2得到的结果都会太大,我们只需记住这个丑数的位置,每次生成新的丑数时更新这个T2,同样对于其他的质数也存在同样的T3,T5等,把这个数组记录为index[].
代码:
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
if (n==1) return 1;
int primesnum=primes.size();
vector<int>index(primesnum,0);
vector<int>ugly(n,INT_MAX);
ugly[0]=1;
for (int i=1; i<n; i++)
{
for (int j=0; j<primesnum; j++)
{
ugly[i]=min(ugly[i],ugly[index[j]]*primes[j]);
}
for (int j=0; j<primesnum; j++)
{
while((ugly[index[j]]*primes[j])<=ugly[i])
index[j]++;
}
}
return ugly[n-1];
}
};