Created
August 25, 2015 01:59
-
-
Save fever324/29dcb8cad53cc6c94809 to your computer and use it in GitHub Desktop.
Nth Ugly Number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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. | |
*/ | |
public class Solution { | |
public int nthUglyNumber(int n) { | |
PriorityQueue<Long> q = new PriorityQueue<Long>(); | |
q.offer(1l); | |
long current = 0; | |
while(n-- > 0) { | |
while(q.peek() == current){ | |
q.poll(); | |
} | |
current = q.poll(); | |
q.offer(current*2); | |
q.offer(current*3); | |
q.offer(current*5); | |
} | |
return (int)current; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment