原题链接在这里:https://leetcode.com/problems/count-primes/
题目:
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.
题解:
网上查查,原来有一种方法叫:Sieve of Eratosthenes 的方法.
Time Complexity: O(nloglogn).
Space: O(n).
AC Java:
1 public class Solution { 2 public int countPrimes(int n) { 3 if(n < 3){ 4 return 0; 5 } 6 boolean [] isPrime = new boolean[n]; 7 Arrays.fill(isPrime, true); 8 int res = n-2; 9 for(int i = 2; i*i<n; i++){ 10 if(isPrime[i]){ 11 for(int j = i; i*j<n; j++){ 12 if(isPrime[i*j]){ 13 isPrime[i*j] = false; 14 res--; 15 } 16 } 17 } 18 } 19 return res; 20 } 21 }