4.8周三

做题

力扣204:计算从2~n-1的质数的数量。
看了一个高效算法,基本思想就是,如果2是质数,那么22 23 24 25 … 就都不是质数。并且由于12 = 26 = 34 = 43 = 62 在12的根号之后,会有计算重复,所以需要检测的质数只需要小于n的平方即可,可以大大缩短计算时间。

class Solution {
    public int countPrimes(int n) {
        
        boolean[] isPrim = new boolean[n];
        Arrays.fill(isPrim,true);
        
        for(int i=2;i*i<n;i++){
            if(isPrimes(i)){//如果i是质数,那么与i相乘的数就都不是质数
                for(int j=2;j*i<n;j++){
                    isPrim[j*i] = false;
                }
            }
        }
        
        int count = 0;
        for(int i=2;i<n;i++){
            if(isPrim[i] == true) count++;
        }
        return count;
    }
    
    public boolean isPrimes(int n){
        for(int i=2;i*i<n;i++){
            if(n%i == 0) return false;
        }
        return true;
    }    
}

力扣面试题13:机器人移动的距离,机器人从(0,0)开始每次只能移动一格,并且不能移动到每位数之和大于k的格子。
使用广搜的思想,每次只要向右或者向下就可以简历完整个地图,只要遇到边界、每位数和大于k或者已经遍历过,就直接返回。这里还需要建立一个标记有没有被访问的数组mark。

class Solution {

    int count;
    int row;
    int column;
    boolean[][] mark;

    public int movingCount(int m, int n, int k) {
        this.count = 0;
        this.row = m;
        this.column = n;
        mark = new boolean[m][n];
        helper(0,0,k);
        return count;
    }
    public void helper(int i, int j, int k){

        if(i<row && j<column) {
            if(mark[i][j] == true) return;
            if(isLarger(i,j,k)) return;
            count++;
            mark[i][j] = true;
            helper(i,j+1,k);//向下
            helper(i+1,j,k);//向右
        }
        
        return;
    }
    public boolean isLarger(int m, int n, int k){
        int result = 0;
        while(m>0) {
            result += m%10;
            m /= 10;
        }
        while(n>0) {
            result += n%10;
            n /= 10;
        }
        return result > k;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值