丑数 II

lc 264. 丑数 II

Description

编写一个程序,找出第 n 个丑数。
丑数就是只包含质因数 2, 3, 5 的正整数。

示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。

说明:  
1 是丑数。
n 不超过1690。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ugly-number-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Solution1

res[0] = 1
然后用res[0]乘以{2,3,5},放进最小堆中,从堆中取出堆顶,即为res[1]。
res[1] = 2
然后用res[1]乘以{2,3,5},放进最小堆中,从堆中取出堆顶,即为res[2]。
循环到 n 即可。
PriorityQueue

class Solution {
    public int nthUglyNumber(int n) {
        int[] ele = new int[]{2,3,5};
        PriorityQueue<Long> q = new PriorityQueue<>();
        long[] res = new long[n];
        res[0] = 1;
        for(int i=0;i<res.length;i++){
            for(int j=0;j<ele.length;j++){
                if(!q.contains((long)(res[i]*ele[j]))){
                    q.add((long)(res[i]*ele[j]));
                }
            }
            if(i+1<res.length){
                res[i+1]=q.poll();
            }
        }
        return (int)res[n-1];
    }
}

Solution2

我们知道丑数序列是 1, 2, 3, 4, 5, 6, 8, 9…。

我们所有的丑数都是通过之前的丑数乘以 2, 3, 5 生成的,所以丑数序列可以看成下边的样子。

1, 1×2, 1×3, 2×2, 1×5, 2×3, 2×4, 3×3…。

我们可以把丑数分成三组,用丑数序列分别乘 2, 3, 5 。

乘 2: 1×2, 2×2, 3×2, 4×2, 5×2, 6×2, 8×2,9×2,…
乘 3: 1×3, 2×3, 3×3, 4×3, 5×3, 6×3, 8×3,9×3,…
乘 5: 1×5, 2×5, 3×5, 4×5, 5×5, 6×5, 8×5,9×5,…
我们需要做的就是把上边三组按照顺序合并起来。

合并有序数组的话,可以通过归并排序的思想,利用三个指针,每次找到三组中最小的元素,然后指针后移。

当然,最初我们我们并不知道丑数序列,我们可以一边更新丑数序列,一边使用丑数序列。

public int nthUglyNumber(int n) {
    int[] ugly = new int[n];
    ugly[0] = 1; // 丑数序列
    int index2 = 0, index3 = 0, index5 = 0; //三个指针
    for (int i = 1; i < n; i++) {
        // 三个中选择较小的
        int factor2 = 2 * ugly[index2];
        int factor3 = 3 * ugly[index3];
        int factor5 = 5 * ugly[index5];
        int min = Math.min(Math.min(factor2, factor3), factor5);
        ugly[i] = min;//更新丑数序列
        if (factor2 == min)
            index2++;
        if (factor3 == min)
            index3++;
        if (factor5 == min)
            index5++;
    }
    return ugly[n - 1];
}

这里需要注意的是,归并排序中我们每次从两个数组中选一个较小的,所以用的是 if…else…。
这里的话,用的是并列的 if , 这样如果有多组的当前值都是 min,指针都需要后移,从而保证 ugly 数组中不会加入重复元素。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值