您的位置:首页 > 其它

204 Count Primes

2015-08-03 17:58 267 查看
题目链接: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
;
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: