lintcode-medium-Ugly Number II

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);
    }
    
};

 

posted @ 2016-04-07 06:13  哥布林工程师  阅读(175)  评论(0编辑  收藏  举报