首页 > 其他 > 详细

lintcode-medium-Ugly Number II

时间:2016-04-07 07:09:10      阅读:314      评论:0      收藏:0      [点我收藏+]

Ugly number is a number that only have factors 23 and 5.

Design an algorithm to find the nth ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...

 

Notice

Note that 1 is typically treated as an ugly number.

Example

If n=9, return 10.

Challenge

O(n log n) or O(n) time.

 

class Solution {
    /**
     * @param n an integer
     * @return the nth prime number as description.
     */
    public int nthUglyNumber(int n) {
        // Write your code here
        
        if(n <= 0)
            return 0;
        
        ArrayList<Integer> res = new ArrayList<Integer>();
        res.add(1);
        
        int cur = 1;
        int p1 = 0;
        int p2 = 0;
        int p3 = 0;
        
        int min1 = 1;
        int min2 = 1;
        int min3 = 1;
        
        while(res.size() < n){
            
            while(res.get(p1) * 2 <= cur)
                p1++;
            min1 = res.get(p1) * 2;
            
            while(res.get(p2) * 3 <= cur)
                p2++;
            min2 = res.get(p2) * 3;
            
            while(res.get(p3) * 5 <= cur)
                p3++;
            min3 = res.get(p3) * 5;
            
            int next = Math.min(min1, Math.min(min2, min3));
            
            res.add(next);
            cur = next;
        }
        
        return res.get(n - 1);
    }
    
};

 

lintcode-medium-Ugly Number II

原文:http://www.cnblogs.com/goblinengineer/p/5361970.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!