标签:
O(n). index_x保存以上一次增长之前的数字位置,factor_x记录当前最小的可能
1 public int nthUglyNumber(int n) { 2 if(n <= 0) { 3 return 0; 4 } 5 int idx2 = 0, idx3 = 0, idx5 = 0; 6 int factor2 = 2, factor3 = 3, factor5 = 5; 7 int[] ugly = new int[n]; 8 ugly[0] = 1; 9 for(int i = 1; i < n; i++) { 10 ugly[i] = Math.min(factor2, Math.min(factor3, factor5)); 11 if(ugly[i] == factor2) { 12 factor2 = ugly[++idx2] * 2; 13 } 14 if(ugly[i] == factor3) { 15 factor3 = ugly[++idx3] * 3; 16 } 17 if(ugly[i] == factor5) { 18 factor5 = ugly[++idx5] * 5; 19 } 20 } 21 return ugly[n-1]; 22 }
标签:
原文地址:http://www.cnblogs.com/warmland/p/5767557.html