zoukankan      html  css  js  c++  java
  • [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 题目总结

  • 相关阅读:
    作业2 求题目中的数
    2013 C#单元测试
    实现项目WC
    带括号多项式版四则运算
    20道简单加减法随机生成程序扩展版体会
    20道简单加减法随机生成程序
    Jeesite 集成微信支付接口
    第一节:JAVA 语言的学习目标
    vector(未完)
    关于phpstorm端口63342的修改经历
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11717484.html
Copyright © 2011-2022 走看看