Description:
Count the number of prime numbers less than a non-negative number, n.
思路分析:這題是一道數學題,求小於n的所有質數。容易想到的思路是定義個isPrime的判定函數,對小於n的數一個一個判定,但是時間複雜度O(N^2)。有沒有更快的算法呢?有,這是一個經典的找質數的算法,Sieve of Eratosthenes,名字雖然比較奇怪,但是其實是一個很簡單易懂的算法,wiki上有一張圖,生動顯示了找質數的過程:
簡而言之,就是初始假定所有數都是質數,然後從2+2開始,劃掉2+2×2,2+2×3...也就是把2的所有倍數劃掉(不含2,因爲2是質數),同理然後把3的所有倍數劃掉,以此類推,如果i是質數,那麼把i的所有倍數劃掉,最後數一下剩下來的質數個數即可。時間複雜度 O(n log log n),空間複雜度是O(n)。當然下面的code還有可以優化的地方,比如定義isNotPrime數組,避免開始遍歷一遍所有數組,默認爲false,最後的count過程也可以寫進前面的遍歷過程,減少遍歷次數,但是時間複雜度還是不改變。
AC Code
public class Solution {
public int countPrimes(int n) {
if(n <= 2) return 0;
boolean isPrime[] = new boolean[n+1];
for(int i = 2; i < n; i++){
isPrime[i] = true;
}
for(int i = 2; i < Math.sqrt(n); i++){
if(isPrime[i]){
for(int j = i+i; j < n; j = j + i){
isPrime[j] = false;
}
}
}
int count = 0;
for(int i = 2; i < n; i++){
if(isPrime[i]){
count++;
}
}
return count;
}
}