lintcode-medium-Ugly Number II

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }
    
};

 

以上是关于lintcode-medium-Ugly Number II的主要内容,如果未能解决你的问题,请参考以下文章