Skip to content

Commit 2f9c932

Browse files
committed
upload 1 answer, Aug 18th
1 parent a5ee362 commit 2f9c932

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Diff for: Medium/UglyNumberII.java

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
Write a program to find the n-th ugly number.
3+
4+
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.
5+
6+
Note that 1 is typically treated as an ugly number.
7+
8+
Hint:
9+
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
10+
An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
11+
The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
12+
Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5)
13+
*/
14+
15+
public class UglyNumberII {
16+
public int nthUglyNumber(int n) {
17+
if (n < 1) return 0;
18+
Queue<Long> queue2 = new LinkedList<>();
19+
Queue<Long> queue3 = new LinkedList<>();
20+
Queue<Long> queue5 = new LinkedList<>();
21+
queue2.add(1l); // long
22+
long val = 0;
23+
for (int i = 0; i < n; i++) {
24+
long v2 = queue2.isEmpty() ? Long.MAX_VALUE : queue2.peek();
25+
long v3 = queue3.isEmpty() ? Long.MAX_VALUE : queue3.peek();
26+
long v5 = queue5.isEmpty() ? Long.MAX_VALUE : queue5.peek();
27+
val = Math.min(v2, Math.min(v3, v5));
28+
if (val == v2) {
29+
queue2.poll();
30+
queue2.add(val*2);
31+
queue3.add(val*3);
32+
}
33+
else if (val == v3) {
34+
queue3.poll();
35+
queue3.add(val*3);
36+
}
37+
else
38+
queue5.poll();
39+
queue5.add(val*5);
40+
}
41+
return (int)val;
42+
}
43+
}
44+
45+
/*
46+
https://leetcode.com/discuss/52710/java-solution-with-three-queues
47+
https://leetcode.com/discuss/52716/o-n-java-solution
48+
https://leetcode.com/discuss/52739/share-clear-accepted-solution-using-queues-with-explanation
49+
https://leetcode.com/discuss/52746/java-solution-using-priorityqueue-o-n
50+
*/

0 commit comments

Comments
 (0)