LEETCode 264. Ugly Number II

问题描述:

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

找第N个丑数,最基础的从1开始判断的方法就不说了,此处的方法是剑指offer上的思路。从1开始遍历的方法复杂度太高,这里只需要考虑到从小到大的开始的每个丑数,都是他前面某个数的2或3或5倍,,因此从已有的丑数1出发,分别诚乘以2、3、5,找出其中最小的一个,得到第二个丑数为2,再找第三个丑数的时候,就要注意到到,由于1乘以2已经出现了,因此下一次是2*2,1*3,1*5,后面的逻辑类似。要注意的时,会出现下一个丑数同时满足多个条件。如6 满足 2*3  也满足3*2  此时 对应的都要更新,不能只更新第一个,所以代码中用的是三个if,而不能是if 、else if

AC代码如下:

  int minThree(int x,int y,int z)
    {
        int temp = x < y ? x : y;
        return temp < z ? temp : z;
    }
    int nthUglyNumber(int n) 
    {
        int count = 0;
        int *ugly = new int[n];
        memset(ugly,0,sizeof(int)*n);
        int index1,index2,index3;
        index1 = index2 = index3 = 0;
        ugly[0] = 1;
        while(count < n-1)
        {
            int No = minThree(2*ugly[index1],3*ugly[index2],5*ugly[index3]);
            if(No == 2*ugly[index1])
            {
                index1++;
            }
            if(No == 3*ugly[index2])
            {
                index2++;
            }
            if(No == 5*ugly[index3])
            {
                index3++;
            }
            count++;
            ugly[count] = No;
        }
        return ugly[count];
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值