原题链接在这里:https://leetcode.com/problems/count-primes/
题目:
Description:
Count the number of prime numbers less than a non-negative number, n.
题解:
网上查查,原来有一种方法叫:Sieve of Eratosthenes 的方法。时间复杂度为O(nloglogn),空间复杂度为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 }