Ugly Number II
TLE解法:
public class Solution { public int nthUglyNumber(int n) { int count = 0; int i = 1; while(count<n){ if(isugly(i)){ count++; } i++; } return i; } public boolean isugly(int n){ if(n == 1) return true; while(n%2==0)n /= 2; while(n%3 == 0) n/=3; while(n%5==0)n/=5; if(n == 1) return true; else return false; } }
AC解法:
可以将丑数分成三个队列
l1:1*2,2*2,3*2,4*2,5*2,6*2,8*2……
l2:1*3,2*3,3*3,4*3,5*3,6*3,8*3……
l3:1*5,2*5,3*5,4*5,5*5,6*5,8*5……
每次从三个队列中拿出队头的数比较,最小的数为当前ith的丑数,循环操作直到为i<n,就找到了nth的丑数。代码:
public class Solution { public int nthUglyNumber(int n) { int r = 0; List <Integer> l1 = new LinkedList<Integer>(); List <Integer> l2 = new LinkedList<Integer>(); List <Integer> l3 = new LinkedList<Integer>(); l1.add(1); l2.add(1); l3.add(1); for(int i = 0;i<n;i++){ r = l1.get(0)<l2.get(0)?(l1.get(0)<l3.get(0)?l1.get(0):l3.get(0)):(l2.get(0)<l3.get(0)?l2.get(0):l3.get(0)); if(l1.get(0)==r)l1.remove(0); if(l2.get(0)==r)l2.remove(0); if(l3.get(0)==r)l3.remove(0); l1.add(r*2); l2.add(r*3); l3.add(r*5); } return r; } }