【leetcode】204. Count Primes
程序员文章站
2022-07-15 09:40:02
...
题目:
Count the number of prime numbers less than a non-negative number, n.
【豚豚】可恶!被骗去洗澡了啊啊啊啊啊啊啊啊啊啊啊啊!!
思路:
Discuss区中有人在评论区发的一个gif图(如下图),很直观。
代码实现:
class Solution {
public:
int countPrimes(int n) {
if (n <= 2){
return 0;
}
if (n == 3){
return 1;
}
vector<bool> isPrime(n+1, 1);
isPrime[2] = 1;
isPrime[3] = 1;
int ret = n-1-1;
for (int i = 2; i < sqrt(n); ++i){
if (isPrime[i] == 1){
for (int j = 2; j*i < n; ++j){
if (isPrime[j*i] == 1){
isPrime[j*i] = 0;
--ret;
}
}
}
}
return ret;
}
};
参考:
https://leetcode.com/problems/count-primes/discuss/57588/My-simple-Java-solution
推荐阅读
-
LeetCode - 38. Count and Say(36ms)
-
leetcode【字符串】-----38. Count and Say(报数)
-
Leetcode1-100: 38. Count and Say
-
LeetCode 38. Count and Say 报数(Java)
-
LeetCode 204. 计数质数 263. 丑数 264. 丑数 II
-
【Hard 递归 动态规划 回文串15】LeetCode 730. Count Different Palindromic Subsequences
-
Leetcode#204. Count Primes
-
LeetCode 204. Count Primes
-
LeetCode ---204. Count Primes
-
【leetcode】204. Count Primes