原题:
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
就是求小于某数的所有质数数量,如果暴力一个一个试着求肯定超时,一种稍微优化的方法是用数组存储所有求出的质数并且在判断一个数是否是质数时只用数组中的元素,结果:
Success
Runtime: 296 ms, faster than 16.29% of C++ online submissions for Count Primes.
Memory Usage: 11.3 MB, less than 23.51% of C++ online submissions for Count Primes.
代码:
class Solution {
public:
int countPrimes(int n) {
if(n<=2){return 0;}
vector<int> prime;
prime.push_back(2);
int j=3;
while(j<n){
bool isprime=1;
for(int i=0;prime[i]<=sqrt(j);i++){
if(j%prime[i]==0){isprime=0;break;}
}
if(isprime){prime.push_back(j);}
j++;
}
return prime.size();
}
};
可以看出无论是时间还是空间复杂度都比较高,然后没想到什么好的解决办法,看了discuss以后发现一个不错的算法,就是设置一个bool数组用来表示一个数是否是质数,如果是就把这个数整数倍的所有数设置成非质数,结果:
Success
Runtime: 20 ms, faster than 96.23% of C++ online submissions for Count Primes.
Memory Usage: 9.9 MB, less than 32.70% of C++ online submissions for Count Primes.
代码:
class Solution
{
public:
int countPrimes(int n)
{
if(n<=2){return 0;}
bool notprime[n]={0};
notprime[0]=1;
notprime[1]=1;
for(int i=2;i<=sqrt(n);i++){
if(!notprime[i]){
for(int j=2*i;j<n;j+=i){
notprime[j]=1;
}
}
}
int cnt=0;
for(int i=0;i<n;i++){if(!notprime[i]){cnt++;}}
return cnt;
}
};