Skip to content

Instantly share code, notes, and snippets.

@fever324
Created August 25, 2015 01:59
Show Gist options
  • Save fever324/29dcb8cad53cc6c94809 to your computer and use it in GitHub Desktop.
Save fever324/29dcb8cad53cc6c94809 to your computer and use it in GitHub Desktop.
Nth Ugly Number
/*
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