题目描述:
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.public class Solution { public int nthUglyNumber(int n) { int u = 0; Deque<Integer> l1 = new ArrayDeque<Integer>(); Deque<Integer> l2 = new ArrayDeque<Integer>(); Deque<Integer> l3 = new ArrayDeque<Integer>(); l1.offer(1); l2.offer(1); l3.offer(1); for(int i=0; i<n; i++) { u = Math.min( Math.min(l1.peek(), l2.peek()), l3.peek()); if(l1.peek() == u) l1.poll(); if(l2.peek() == u) l2.poll(); if(l3.peek() == u) l3.poll(); l1.offer(u*2); l2.offer(u*3); l3.offer(u*5); } return u; } }