码迷,mamicode.com
首页 > 其他好文 > 详细

264. Ugly Number II

时间:2016-08-13 11:21:37      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:

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     }

 

264. Ugly Number II

标签:

原文地址:http://www.cnblogs.com/warmland/p/5767557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!