牛客网--丑数(时间空间效率的平衡)

题目:

把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

知识点:

穷举

思路:

1、建立一个长度为N的数组:存放从小到大排列的数。

2、三个下标:i2,i3,i5:分别指向{2,3,5}中每个数达到了哪一步,进行判断当前的最小值。

最小数的下标:count

3、最开始最小数组中的数为1,i2=0,i3=0,i5=0,count=0;

(1)1,下标为0,0,0

* 2

* 3

* 5

(2)1 2,下标为1,0,0

2 * 4

*3

*5

(3)1 2 3,下标为1,1,0

2 * 4

3 * 6

*5

(4)1 2 3 4,下标为2,1,0

2 4 * 6

3 * 6

* 5

......

依次类推,每次将最小的放入数组,并将存入数组那一行的下标向后移一位。

答案:

public class Solution {
    public int GetUglyNumber_Solution(int index) {
        if(index<=0){return 0;}
        int[] result = new int[index];
        int count = 0;
        int i2 = 0;
        int i3= 0;
        int i5 = 0;
        result[0] = 1;
        int tmp=0;
        while(count<index-1){
            tmp = min(result[i2]*2,min(result[i3]*3,result[i5]*5));
            if(tmp == result[i2]*2){i2++;}
            if(tmp == result[i3]*3){i3++;}
            if(tmp == result[i5]*5){i5++;}
            result[++count]=tmp;
        }
        return result[index-1];
    }
    public int min(int a,int b){
        return (a>b)?b:a;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值