zoukankan      html  css  js  c++  java
  • LeetCode 204. Count Primes (质数的个数)

    Description:

    Count the number of prime numbers less than a non-negative number, n.


     题目标签:Hash Table

      题目给了我们一个n, 让我们找出比n小的 质数的数量。

    因为这道题目有时间限定,不能用常规的方法。

    首先建立一个boolean[] nums,里面初始值都是false,利用index 和 boolean 的对应,把所有prime number = false;non-prime number = true。

    遍历nums array:(从index 2开始,因为1不是prime number)

      只对是false 的数字进行操作:

        1. 首先count,因为 false = prime number;

        2. 把 index(数字) * 2,3,4,....  去到对应的nums[index * 2,3,4...] 的位置里把 non-prime number 的值 改成 true。

          因为是从2 开始的,prime number 只能被1 和 自己所除, 换句话说 prime = prime * 1。所以两个 大于1 的数字 a * b 是不会找到 prime number 的。

    Java Solution:

    Runtime beats 81.95% 

    完成日期:05/26/2017

    关键词:boolean[] nums

    关键点:遍历每一个prime number,利用这个number * 2,3,4... 把之后的non-prime标记出来

     1 class Solution 
     2 {
     3     public int countPrimes(int n) 
     4     {
     5         int count = 0;
     6         boolean[] nums = new boolean[n]; // prime = false; non-prime = true
     7         
     8         for(int i=2; i<n; i++) // iterate from 2 to (n-1)
     9         {
    10             if(!nums[i]) // only access when this num is false
    11             {
    12                 count++; // if a num is false meaning this number is prime
    13                 
    14                 int m = 2; // multiplier
    15                 while(i * m < n) // mark all the non-prime numbers
    16                 {
    17                     nums[i*m] = true;
    18                     m++;
    19                 }
    20             }   
    21         }
    22         
    23         return count;
    24     }
    25 }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

  • 相关阅读:
    pat 甲级 1065. A+B and C (64bit) (20)
    pat 甲级 1064. Complete Binary Search Tree (30)
    pat 甲级 1010. Radix (25)
    pat 甲级 1009. Product of Polynomials (25)
    pat 甲级 1056. Mice and Rice (25)
    pat 甲级 1078. Hashing (25)
    pat 甲级 1080. Graduate Admission (30)
    pat 甲级 团体天梯 L3-004. 肿瘤诊断
    pat 甲级 1099. Build A Binary Search Tree (30)
    Codeforce 672B. Different is Good
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7741110.html
Copyright © 2011-2022 走看看