forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSuper Ugly Number.java
83 lines (62 loc) · 1.95 KB
/
Super Ugly Number.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//---------------------O(nlogk)-------------------------
class Solution {
public int nthSuperUglyNumber(int n, int[] primes) {
int []dp=new int[n+1];
dp[1]=1;
PriorityQueue<Pair> pq=new PriorityQueue<>();
for(int i=0;i<primes.length;i++){
pq.add(new Pair(primes[i],1,primes[i]));
}
for(int i=2;i<=n;){
Pair curr=pq.remove();
if(curr.val!=dp[i-1]){
dp[i]=curr.val;
i++;
}
int newval=curr.prime*dp[curr.ptr+1];
if(newval>0){
pq.add(new Pair(curr.prime, curr.ptr+1,newval));
}
}
return dp[n];
}
}
class Pair implements Comparable<Pair>{
int prime;
int ptr;
int val;
public Pair(int prime, int ptr, int val){
this.prime=prime;
this.ptr=ptr;
this.val=val;
}
public int compareTo(Pair o){
return this.val-o.val;
}
}
//-----------------------O(nk)---------------------------
// class Solution {
// public int nthSuperUglyNumber(int n, int[] primes) {
// int []dp=new int[n+1];
// dp[1]=1;
// int []ptr=new int[primes.length];
// Arrays.fill(ptr,1);
// for(int i=2;i<=n;i++){
// int min=Integer.MAX_VALUE;
// for(int j=0;j<ptr.length;j++){
// int val=dp[ptr[j]]*primes[j];
// if(val>0){
// min=Math.min(min,val);
// }
// }
// dp[i]=min;
// for(int j=0;j<ptr.length;j++){
// int val=dp[ptr[j]]*primes[j];
// if(val>0 && min==val){
// ptr[j]++;
// }
// }
// }
// return dp[n];
// }
// }