204 Count Primes

题目链接:https://leetcode.com/problems/count-primes/

题目:

Description:

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Hint:

Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?

解题思路:
厄拉多塞筛法
每找到一个素数,就将其倍数抹去。最终留下的都是素数。
参考链接:https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
在代码中,先创建一个长度为 n 的数组(数组为布尔类型),将数组元素全部赋值为 true。从下标为2开始遍历数组,若元素值为 true,count 加一,并将数组下标为其下标倍数的元素赋值为 false;若元素为 false,就跳出本次循环。

注意:
用 ArrayList 来存储,会超时!

public class Solution {
    public int countPrimes(int n) {
        int count = 0;
        boolean[] buf = new boolean[n];
        for(int i = 0; i < n; i ++)
            buf[i] = true;
        for(int i = 2; i < n; i ++) {
            if(buf[i] == false)
                continue;
            for(int j = i + i; j < n; j = j + i)
                buf[j] = false;
            count ++;
        }
        return count;
    }
}
20 / 20 test cases passed.
Status: Accepted
Runtime: 288 ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值