204 Count Primes

来源:互联网 发布:淘宝五钻店铺多少钱 编辑:程序博客网 时间:2024/05/08 09:44

题目链接: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: AcceptedRuntime: 288 ms
0 0
原创粉丝点击