丑数

首先从丑数的定义我们知道,一个丑数的因子只有2,3,5,那么丑数p = 2 ^ x * 3 ^ y * 5 ^ z,换句话说一个丑数一定由另一个丑数乘以2或者乘以3或者乘以5得到,那么我们从1开始乘以2,3,5,就得到2,3,5三个丑数,在从这三个丑数出发乘以2,3,5就得到4,6,10,6,9,15,10,15,25九个丑数,我们发现这种方法会得到重复的丑数,而且我们题目要求第N个丑数,这样的方法得到的丑数也是无序的。那么我们可以维护三个队列: 

(1)丑数数组: 1 

乘以2的队列:2 

乘以3的队列:3 

乘以5的队列:5 

选择三个队列头最小的数2加入丑数数组,同时将该最小的数乘以2,3,5放入三个队列; 

(2)丑数数组:1,2 

乘以2的队列:4 

乘以3的队列:3,6 

乘以5的队列:5,10 

选择三个队列头最小的数3加入丑数数组,同时将该最小的数乘以2,3,5放入三个队列; 

(3)丑数数组:1,2,3 

乘以2的队列:4,6 

乘以3的队列:6,9 

乘以5的队列:5,10,15 

选择三个队列头里最小的数4加入丑数数组,同时将该最小的数乘以2,3,5放入三个队列; 

(4)丑数数组:1,2,3,4 

乘以2的队列:6,8 

乘以3的队列:6,9,12 

乘以5的队列:5,10,15,20 

选择三个队列头里最小的数5加入丑数数组,同时将该最小的数乘以2,3,5放入三个队列; 

(5)丑数数组:1,2,3,4,5 

乘以2的队列:6,8,10, 

乘以3的队列:6,9,12,15 

乘以5的队列:10,15,20,25 

选择三个队列头里最小的数6加入丑数数组,但我们发现,有两个队列头都为6,所以我们弹出两个队列头,同时将12,18,30放入三个队列; 

实现一:

public int GetUglyNumber_Solution(int index) {
        if (index < 7){
            return index;
        }
        Queue<Integer> queue2 = new ConcurrentLinkedQueue<Integer>();
        Queue<Integer> queue3 = new ConcurrentLinkedQueue<Integer>();
        Queue<Integer> queue5 = new ConcurrentLinkedQueue<Integer>();

        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        queue2.add(list.get(list.size() - 1) * 2);
        queue3.add(list.get(list.size() - 1) * 3);
        queue5.add(list.get(list.size() - 1) * 5);
        int num;
        while (list.size() < index){
            num = Math.min(queue2.peek(),Math.min(queue3.peek(),queue5.peek()));
            if (queue2.contains(num)){
                queue2.poll();
            }
            if (queue3.contains(num)){
                queue3.poll();
            }
            if (queue5.contains(num)){
                queue5.poll();
            }
            list.add(num);
            queue2.add(list.get(list.size() - 1) * 2);
            queue3.add(list.get(list.size() - 1) * 3);
            queue5.add(list.get(list.size() - 1) * 5);
        }
        return list.get(list.size() - 1);

    }

实现二:降低空间复杂度

    public int GetUglyNumber_Solution(int index) {
        if (index < 7){
            return index;
        }
        int p2 = 0, p3 = 0, p5 = 0, num = 0;
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        while (list.size() < index){
            num = Math.min(list.get(p2) * 2,Math.min(list.get(p3) * 3,list.get(p5) * 5));
            if (list.get(p2) * 2 == num){
                p2 ++;
            }
            if (list.get(p3) * 3 == num){
                p3 ++;
            }
            if (list.get(p5) * 5 == num){
                p5 ++;
            }
            list.add(num);
        }
        return list.get(list.size() - 1);
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值