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:
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.方法一: Priority Queue, 取出最小值乘以2,3,5, 加入到Heap中,然后再取出最小值,循环n-1次,最后得到的最小值就是结果。因为用到了现成的Priority Queue, 花时间较多。
方法二: declared three counter variables: a,b,and c which represent the corresponding index in the arraylist for the multiplier of 2,3,and 5. Since each previous ugly number times one of the multiplier will produce a new ugly number, I start from the starting index 0 and multiply the ugly number at that index with each multiplier and get the smallest product which is the next ugly number from the three. The corresponding multipliers‘ index will be incremented by one and we do this recursively until we have K ugly numbers.
Java code:
方法一:
public class Solution { public int nthUglyNumber(int n) { if(n == 1){ return 1; } PriorityQueue<Long> q = new PriorityQueue<Long>(); q.add(1l); for(long i = 1; i < n; i++) { long tmp = q.poll(); while(!q.isEmpty() && q.peek() == tmp) { tmp = q.poll(); } q.add(tmp*2); q.add(tmp*3); q.add(tmp*5); } return q.poll().intValue(); } }
方法二:
public class Solution { public int nthUglyNumber(int n) { if(n == 1) { return 1; } ArrayList<Integer> list = new ArrayList<Integer>(); int a = 0, b = 0, c = 0; list.add(1); for(int i = 1; i < n; i++) { int nextVal = Math.min(Math.min(list.get(a) * 2, list.get(b) * 3), list.get(c) * 5); list.add(nextVal); if(nextVal == list.get(a) * 2) { a++; } if(nextVal == list.get(b) * 3) { b++; } if(nextVal == list.get(c) * 5) { c++; } } return list.get(n-1); } }
Reference:
1. https://leetcode.com/discuss/59825/java-solution-using-priorityqueue
2. https://leetcode.com/discuss/55304/java-easy-understand-o-n-solution
原文:http://www.cnblogs.com/anne-vista/p/4896565.html