4. Ugly Number II

Ugly number is a number that only have factors 2, 3 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...

Example
If n=9, return 10.

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

Notice
Note that 1 is typically treated as an ugly number.
public class Solution {
    /**
     * @param n: An integer
     * @return: the nth prime number as description.
     */
    public int nthUglyNumber(int n) {
        if(n <= 0) return 0;
        if(n == 1) return 1;
        int[] res = new int[n];
        res[0] = 1;
        int index2 = 0, index3 = 0, index5 = 0;
        for(int i = 1; i < n; i++){
            int res2 = 2*res[index2], res3 = 3*res[index3], res5 = 5*res[index5];
            int tmp = Math.min(Math.min(res2, res3), res5);
            if(tmp == res2) index2++;
            if(tmp == res3) index3++;
            if(tmp == res5) index5++;
            res[i] = tmp;
        }
        return res[n-1];
    }
}
//还有一种方法是用PriorityQueue
class Solution {
    /**
     * @param n an integer
     * @return the nth prime number as description.
     */
    public int nthUglyNumber(int n) {
        // Write your code here
        Queue<Long> pq = new PriorityQueue<Long>();
        // 用一个set来避免有重复的元素出现
        // 每次都弹出最小的值,然后用这个值去乘235,只要没有重复就加进去
        // 用pq的好处是避免了去找最小值,pq每次poll出来的都是满足条件的ugly number的最小值
        // 但是每次都会加三个数进pq
        HashSet<Long> set = new HashSet<Long>();
        Long[]base = new Long[3];
        base[0] = (long)2; 
        base[1] = (long)3;
        base[2] = (long)5;
        Long res = (long)1;
        for(int i = 0; i < 3; i++) {
            pq.offer(base[i]);
            set.add(base[i]);
        }
        for(int i = 1; i < n; i++){
            res = pq.poll();
            for(int j = 0; j < 3; j++) {
                long tmp = base[j] * res;
                if(set.contains(tmp)) 
                    continue;
                set.add(tmp);
                pq.offer(tmp);
            }
        }
        return res.intValue();

    }
};
posted on 2019-01-18 07:49 9042 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lawrenceSeattle/p/10285789.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值