题目
LeetCode - 204. Count Primes
题目链接
https://leetcode.com/problems/count-primes/
参考博客
https://www.cnblogs.com/grandyang/p/4462810.html
解题思路
自行设计的算法时间复杂度是 n ∗ n \sqrt{n} * n n∗n,但是运行超时,参考博客的算法复杂度分析知时间复杂度相同,所以这题有点奇怪。
解题源码
- 自行设计代码
class Solution {
public:
set<int> s;
int countPrimes(int n) {
if (n <=1) return 0;
int t = static_cast<int>(pow(n,0.5));
int cnt = 0;
for (int i = 2; i <= t; i++){
for (int j = i; j < n; j++){
if (i*j < n) {
s.insert(i*j);
// cout << i*j << " ";
}
}
}
// cout << endl;
return n - 2 - s.size();
}
};
- 参考博客
class Solution {
public:
int countPrimes(int n) {
vector<bool> Prime(n, true);
int ans = 0;
for(int i = 2; i < n; i++){
if (Prime[i]){
ans++;
for (int j = 2; i*j < n; j++){
Prime[i*j] = false;
}
}
}
return ans;
}
};