[LeetCode] 204. Count Primes

Count the number of prime numbers less than a non-negative number, 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

计数质数。

题意是找出小于N范围内的整数里面所有的质数(prime number)的个数。思路是打表法,在2 ~ N范围内,先找出所有的质数,同时找出这些质数的倍数,标记为false。这样剩下没有被标记到的数字就都是质数了。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int countPrimes(int n) {
 3         boolean[] notPrimes = new boolean[n];
 4         int res = 0;
 5         for (int i = 2; i < n; i++) {
 6             if (!notPrimes[i]) {
 7                 res++;
 8                 for (int j = 2; i * j < n; j++) {
 9                     notPrimes[i * j] = true;
10                 }
11             }
12         }
13         return res;
14     }
15 }

JavaScript实现

 1 /**
 2  * @param {number} n
 3  * @return {number}
 4  */
 5 var countPrimes = function(n) {
 6     let notPrimes = new Array(n);
 7     for (let i = 0; i < n; i++) {
 8         notPrimes[i] = false;
 9     }
10     let res = 0;
11     for (let i = 2; i < n; i++) {
12         if (notPrimes[i] === false) {
13             res++;
14             for (let j = 2; i * j < n; j++) {
15                 notPrimes[i * j] = true;
16             }
17         }
18     }
19     return res;
20 };

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/11717484.html