题目:
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.
Hint:
- 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. - An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
- 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.
- Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
链接: http://leetcode.com/problems/ugly-number-ii/
题解:
数学题again...。大家都要好好学数学。主要思路是参考了Discuss里面的解法,据说使用的是CC150里的方法。首先n = 1时,结果是1。接下来维护三个Queue<Long>, 假如不用Long的话那么n = 1600+的时候就会溢出。利用递推关系分别对q2,q3和q5里的peek()进行比较,然后计算下几个ugly number。
Time Complexity - O(n), Space Compleixty - O(n)
public class Solution { public int nthUglyNumber(int n) { if(n < 1) return 0; Queue<Long> q2 = new LinkedList<>(); Queue<Long> q3 = new LinkedList<>(); Queue<Long> q5 = new LinkedList<>(); q2.add(2l); q3.add(3l); q5.add(5l); Long res = 1l; while(n > 1) { if(q2.peek() < q3.peek() && q2.peek() < q5.peek()) { res = q2.poll(); q2.add(res * 2); q3.add(res * 3); q5.add(res * 5); } else if(q3.peek() < q2.peek() && q3.peek() < q5.peek()) { res = q3.poll(); q3.add(res * 3); q5.add(res * 5); } else { res = q5.poll(); q5.add(res * 5); } n--; } return res.intValue(); } }
Reference:
http://www.geeksforgeeks.org/ugly-numbers/
https://leetcode.com/discuss/52722/short-and-o-n-python-and-c
http://www.stefan-pochmann.info/spocc/
https://leetcode.com/discuss/53009/interesting-bounds-about-this-problem
https://leetcode.com/discuss/53505/using-three-queues-java-solution
https://leetcode.com/discuss/55304/java-easy-understand-o-n-solution
https://leetcode.com/discuss/55307/c-solution-with-o-n-time
https://leetcode.com/discuss/57156/my-expressive-python-solution
https://leetcode.com/discuss/58186/elegant-c-solution-o-n-space-time-with-detailed-explanation
https://leetcode.com/discuss/59825/java-solution-using-priorityqueue
https://leetcode.com/discuss/67877/%08two-standard-dp-solutions
https://leetcode.com/discuss/71549/o-n-java-easy-version-to-understand
https://leetcode.com/discuss/53225/c-one-pass-simple-solution
https://leetcode.com/discuss/52905/my-16ms-c-dp-solution-with-short-explanation
https://leetcode.com/discuss/52710/java-solution-with-three-queues
https://leetcode.com/discuss/52716/o-n-java-solution