https://leetcode.com/problems/count-primes/description/
Description:
Count the number of prime numbers less than a non-negative number, n.
下面给出两段代码,一段用了boolean数组,另一段用的是bitset。(题外话,从运行时间可以看得出来boolean数组是要比bitset操作来的快的。)算法复杂度可以认为是o(nlogn)因为,每个关于j的操作都是logn
public int countPrimes(int n) {
boolean[] notPrime = new boolean[n];
int count = 0;
for (int i = 2; i < n; i++) {
if (!notPrime[i]) {
count++;
for (int j = 2; i * j < n; j++) {
notPrime[i * j] = true;
}
}
}
return count;
} public int countPrimes(int n) {
BitSet bitSet = new BitSet(n);
bitSet.set(Math.min(n, 2), n, true);
for (int i = 2; i < n; i++) {
if (bitSet.get(i)) {
for (int j = 2; i * j < n; j++) {
bitSet.set(i * j, false);
}
}
}
return bitSet.cardinality();
}
727

被折叠的 条评论
为什么被折叠?



