• [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 题目总结

  • 相关阅读:
    设计模式天天练。
    系统资料库msdb置疑或者不可用的解决方法
    依赖注入IOC
    重载、重写、隐藏的区别
    ASP.NET中的HttpWorkerRequest对像及其应用
    ASP.NET的错误处理机制
    Web.Config
    asp.net 2.0页面生命周期
    FileUpLoad控件上传大容量文件
    大文件上传
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11717484.html
Copyright © 2020-2023  润新知