204. Count Primes

Description

Description:

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

Solution

Basic

注意不能用n / 2来减小遍历范围,比如n = 4的话,如果用n / 2来缩小范围,3就没有被处理。
神奇的地方是,用HashSet会超时,改成array就好了。看来如果array范围可控还是用array比较快。
还要注意题目求的是小于n的个数!

class Solution {
    public int countPrimes(int n) {
        boolean[] notPrime = new boolean[n];
        int count = 0;
        
        for (int i = 2; i < n; ++i) {
            if (notPrime[i]) {
                continue;
            }
            ++count;
            for (int j = 2; i * j < n; ++j) {
                notPrime[i * j] = true;
            }
        }
        
        return count;
    }
}

Optimized

偶数可以skip
TODO

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容