Ugly Number II
public int nthUglyNumber(int n) { int[] ugly = new int[n]; ugly[0] = 1; int m2 = 1; int m3 = 1; int m5 = 1; int f2 = 2; int f3 = 3; int f5 = 5; for(int i = 1; i < n; i++) { int min = Math.min(Math.min(f2,f3),f5); ugly[i] = min; if(min == f2){ f2 = 2 * ugly[m2]; m2++; } if(min == f3) { f3 = 3 * ugly[m3]; m3++; } if(f5 == min){ f5 = 5 * ugly[m5]; m5++; } } return ugly[n-1]; }
因为定义的ugly number是2,3,5的倍数, 所以新的ugly number也是由他们的倍数组成. 每次找到三个数中最小的, 然后求它的倍数.
Leave A Comment