Skip to content

Commit 90828c0

Browse files
committed
add solution of problem 313: super ugly number
1 parent c9755aa commit 90828c0

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

SuperUglyNumber313/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
Write a program to find the n<sup>th</sup> super ugly number.
2+
3+
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.
4+
5+
#####Note:
6+
(1) `1` is a super ugly number for any given `primes`.
7+
(2) The given numbers in `primes` are in ascending order.
8+
(3) 0 < `k` ≤ 100, 0 < `n` ≤ 10<sup>6</sup>, 0 < `primes[i]` < 1000.

SuperUglyNumber313/Solution.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
public class Solution {
2+
public int nthSuperUglyNumber(int n, int[] primes) {
3+
if (n <= 0 || primes == null || primes.length == 0)
4+
return 0;
5+
6+
int k = primes.length;
7+
int[] multiplesIdx = new int[k];
8+
int[] product = new int[k];
9+
for (int i = 0; i < k; i++) {
10+
multiplesIdx[i] = 1;
11+
product[i] = primes[i];
12+
}
13+
14+
int[] result = new int[n + 1];
15+
result[1] = 1;
16+
17+
for (int i = 2; i <= n; i++) {
18+
int minValue = product[0];
19+
for (int j = 1; j < k; j++) {
20+
int value = product[j];
21+
if (value < minValue)
22+
minValue = value;
23+
}
24+
25+
result[i] = minValue;
26+
27+
for (int j = 0; j < k; j++) {
28+
if (product[j] == minValue) {
29+
multiplesIdx[j]++;
30+
product[j] = primes[j] * result[multiplesIdx[j]];
31+
}
32+
}
33+
}
34+
35+
return result[n];
36+
}
37+
}

0 commit comments

Comments
 (0)