标签:turn i++ leetcode 思路 class res case https tco
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.
上来直接用的暴力解法,然而有3个case超时了
class Solution {
public int countPrimes(int n) {
int res = 0;
for(int i = 1; i < n; i++) {
if(isPrime(i)) res++;
}
return res;
}
private boolean isPrime(int n) {
int count = 0;
if(n == 1) return false;
for(int i = 1; i * i <= n; i++) {
if(n % i == 0) count++;
}
return count == 1 ? true : false;
}
}
用的是埃拉托斯特尼筛法。
class Solution {
public int countPrimes(int n) {
boolean[] notPrime = new boolean[n];
int count = 0;
for(int i = 2; i < n; i++) { //遍历数组
if(notPrime[i])
continue;
count++;
for(int j = 2; i * j < n; j++)
notPrime[i * j] = true;
}
return count;
}
}
标签:turn i++ leetcode 思路 class res case https tco
原文地址:https://www.cnblogs.com/shinjia/p/9777404.html