leetcode204_Count Primes

Count the number of prime numbers less than a non-negative number, n.

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

一开始写了一个双层遍历的类型,具体如下:

class Solution {
    public int countPrimes(int n) {
        int count=0;
        if(n<=2){return 0;}
        for(int i=2;i<n;i++){
            int flag=0;
            for(int j=2;j<i;j++){
                if(i%j==0){
                    flag=1;
                    break;
                }
            }
            if(flag==0){
                count++;
            }
        }
        return count;
    }
}

报错的原因是在数值较大的时候会超时Time Limit Exceeded

于是把第二层循环写成for(int j=2;j<=i/2;j++)范围从除以i/2到除以i/(i/2)=2还是超时

再继续改成for(int j=2;j<=Math.sqrt(i);j++)范围从除以i/2到除以根号2,不超时了,提交成功,但是运行速度不好。

具体代码如下:

class Solution {
    public int countPrimes(int n) {
        int count=0;
        if(n<=2){return 0;}
        for(int i=2;i<n;i++){
            int flag=0;
            for(int j=2;j<=Math.sqrt(i);j++){
                if(i%j==0){
                    flag=1;
                    break;
                }
            }
            if(flag==0){
                count++;
            }
        }
        return count;
    }
}

参考网上的其他解题思路:

用一个布尔型数组,首先把0~n中不是prime的全部标出来,然后遍历一遍,遇到false的就count++,最后返回count就行。时间复杂度为O(n),(根号n*根号n),空间复杂度为O(n)。

public class Solution {
    public int countPrimes(int n) {
        if (n <= 1) {
            return 0;
        }
        // 默认所有的元素值都会设置为false,从0到n-1一共有n个值
        boolean[] notPrime = new boolean[n];
        //初始化0和1为true,从2开始处理进行标注
        notPrime[0] = true;
        notPrime[1] = true;
        for (int i = 2; i * i < n; i++) {
            // 如果i是一个质数,则将i的倍数设置为非质数
            // 如是i是一个合数,则它必定已经设置为true了,因为是从2开始处理的,所以代码里面就不用处理了

            if (!notPrime[i]) {
                for (int j = 2 * i; j < n; j += i) {
                    notPrime[j] = true;
                }
            }
        }
        // 统计质数的个数
        int count=0;
        for(int k=0;k<n;k++){
            if(!flag[k]){
                count++;
            }
        }
        return count;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值