leetcode263-264丑数

方法1:从头遍历找到第n个,但是会超时的,判断丑数的方法就是,把是2的因子全部去掉,把含5的因子全部去掉,把3的因子全部去掉,看是否是1.

class Solution {
    public int nthUglyNumber(int n) {
        int count=1;
        int i=1;
        while(count<n){
            i++;
            if(ischou(i))  count++;
        }
        return i;
        
    }
    public boolean ischou(int n){
        while(n!=0&&n%2==0) n=n/2;
        while(n!=0&&n%3==0) n=n/3;
        while(n!=0&&n%5==0) n=n/5;
        return n==1;
    }
}

方法2:使用i2,i3,i5三个指针,分别表示乘以2,3,5的位置,开始都指向1位置,然后找三个指针乘以对应数的最小值,即2放在第二个位置,然后看哪个指针乘以对应数等于2,如果等于,将指针位置+1,因为当前不可能再用到他了,他已经出现了,只能放大(即往后移动),这可不是一次只移动一个指针哦,有可能移动两个指针的,三个也可能,只要当前指针乘以对应的数出现了,就必须向下移动一个位置。

class Solution {
    public int nthUglyNumber(int n) {
        int i2=1,i3=1,i5=1,count=1;;
        int[] help=new int[n+1];
        help[1]=1;
        while(count<n){
            help[++count]=Math.min(help[i2]*2,Math.min(help[i3]*3,help[i5]*5));
            if(help[i2]*2==help[count]) i2++;
            if(help[i3]*3==help[count]) i3++;
            if(help[i5]*5==help[count]) i5++;
        }
        return help[n];
    }
}

总结:对于求数列的第几项的问题,都可以这么考虑,就是当前项由前面哪几项影响,得到

1201丑数三
这个方法超时了,这不是就是3n的时间复杂度吗??怎么又卡常数啊,烦

class Solution {
    public int nthUglyNumber(int n, int a, int b, int c) {
        int count=1;
        int i=2;
        while(count<n){
            if(++i%a==0||i%b==0||i%c==0) count++;
        }
        return i;
    }
}

这个题我不知道为啥,我这么做就是错,能过很多case的

class Solution {
    public int nthUglyNumber(int n, int a, int b, int c) {
        int count=0;
        int ia=1,ib=1,ic=1,res=0;
        while(count<n){
            res=Math.min(ia*a,Math.min(ib*b,ic*c));
            if(res==ia*a) ia++;
            if(res==ib*b) ib++;
            if(res==ic*c) ic++;
            count++;
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值