版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85314233
Title:Count Primes 204
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/count-primes/
1. 见代码注释
时间复杂度:O(nlogn),for循环嵌套for。
空间复杂度:O(n),申请boolean类型数组空间。
/**
* 反其道行之:定义一个boolean数组,从2开始叠乘,赋值为true,统计false的个数就是素数的个数
* @param n
* @return
*/
public static int countPrimes(int n) {
if (n <= 1) {
return 0;
}
boolean vin[] = new boolean[n];
int count = 0;
for (int i = 2; i < n; i++) {
if (!vin[i]) {
count++;
}
for (int j = 2; i * j < n; j++) {
vin[i * j] = true;
}
}
return count;
}