LeetCode 204. Count Primes

原题链接在这里:https://leetcode.com/problems/count-primes/

题目:

Given an integer n, return the number of prime numbers that are strictly less than n.

Example 1:

Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Example 2:

Input: n = 0
Output: 0

Example 3:

Input: n = 1
Output: 0

Constraints:

  • 0 <= n <= 5 * 106

题解:

网上查查,原来有一种方法叫:Sieve of Eratosthenes 的方法.

Time Complexity: O(sqrt(n) * loglogn).

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 }

 跟上Perfect Squares

posted @ 2015-08-03 02:57  Dylan_Java_NYC  阅读(204)  评论(0编辑  收藏  举报