LeetCode Count Primes

原题链接在这里:https://leetcode.com/problems/count-primes/

这道题我先用了 HashSet,从2开始判断他是否为prime,若是就加入HashSet,对于接下来的数n,判断它是否会被HashSet现有的数字整除,若不能,n也是prime,加入HashSet;若能,n就不是prime。时间复杂度为O(n+k^2),k为指数。但是这种方法也超时了。


网上查查,原来有一种方法叫:Sieve of Eratosthenes 的方法。时间复杂度为O(nloglogn),空间复杂度为O(n).


Note: 1. 题目说的是less than n, 所以 n 不算, 例如输入为2,返回值应该是0 而不是 1.

  2. 新建的 boolean array 长度是 n+1,因为要算上0, 但这道题目球的是 less than n, 所以建长度为n的也ok。不过要记得在array名字后面加[].

  3. 为什么i要循环到Math.sqrt(n), 因为要保证下面的 j 不overflow 数组,以 5 为例,5*2,5*3,都被之前检查2,检查3时检查过了,所以直接检查5*5 即可,对于每一个i,都是直接开始检查i*i即可,所以外层的i要满足 i < Math.sqrt(n).

  4. j = 2i, 4i, 6i, 循环时要这么写:for(int j = i+i;j<n;j = j+i).


public class Solution {
    public int countPrimes(int n) {
        /*Method 1
        if(n<=1) 
            return 0;
            
        HashSet<Integer> hs = new HashSet<>();
        int counter = 0;
        
        for(int i = 2; i<n;i++){
            if(isPrime(i,hs)){
                hs.add(i);
                counter++;
            }
        }
        
    return counter;    
    }
    
    private boolean isPrime(int n, HashSet hs){
        if(n>1 && (hs == null || hs.size() == 0))
            return true;
        
        Iterator it = hs.iterator();
        while(it.hasNext()){
            int k = (int)it.next();
            if(n%k == 0){
                return false;
            }
        }
        
        return true;
    }
    */
    
        //Method 2 Sieve of Eratosthenes
        if(n<=2) 
            return 0;
    
        boolean isPrime[] = new boolean[n+1];
        for(int i = 2;i<n;i++){
            isPrime[i] = true;
        }
    
        for(int i = 2; i<Math.sqrt(n);i++){
            if(isPrime[i]){
                for(int j = i+i;j<n;j=j+i){
                    isPrime[j] = false;
                }
            }
        }
        
        int count = 0;
        for(int i = 2;i<n;i++){
            if(isPrime[i]){
                count++;
            }
        }
        
        return count;
    
    }
}
        



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值