您的位置:首页 > 其它

LeetCode Count Primes

2015-08-03 02:57 399 查看
原题链接在这里: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;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: