-
Notifications
You must be signed in to change notification settings - Fork 5
/
UglyNumber2.java
55 lines (53 loc) · 1.62 KB
/
UglyNumber2.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
/*https://leetcode.com/problems/ugly-number-ii/*/
class Solution {
public int nthUglyNumber(int n) {
PriorityQueue<Long> minHeap = new PriorityQueue<Long>();
if (n == 1) return 1;
minHeap.add((long)1);
long currentElement = -1;
HashSet<Long> set = new HashSet<Long>();
set.add((long)1);
while (n-- > 0)
{
currentElement = minHeap.poll();
long newElement = currentElement*2;
if (!set.contains(newElement))
{
minHeap.add(newElement);
set.add(newElement);
}
newElement = currentElement*3;
if (!set.contains(newElement))
{
minHeap.add(newElement);
set.add(newElement);
}
newElement = currentElement*5;
if (!set.contains(newElement))
{
minHeap.add(newElement);
set.add(newElement);
}
}
return (int)currentElement;
}
}
class Solution {
static int[] uglyNums = new int[1690];
public int nthUglyNumber(int n) {
if(uglyNums[0] == 1) return uglyNums[n-1];
int a = 0, b = 0, c = 0;
uglyNums[0] = 1;
for(int i = 1; i < 1690; i++){
int mul2 = uglyNums[a] * 2;
int mul3 = uglyNums[b] * 3;
int mul5 = uglyNums[c] * 5;
int min = Math.min(mul2, Math.min(mul3, mul5));
if(min == mul2)a++;
if(min == mul3)b++;
if(min == mul5)c++;
uglyNums[i] = min;
}
return uglyNums[n-1];
}
}