原题链接在这里: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 }

 跟上Perfect Squares

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-06
  • 2022-01-18
猜你喜欢
  • 2021-11-21
  • 2021-04-15
  • 2022-01-02
  • 2021-08-03
  • 2021-07-14
  • 2021-09-25
相关资源
相似解决方案