• Python3解leetcode 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.

    思路:

    1、最暴力的方法就是循环遍历,用两个for循环嵌套实现,但是整个代码运行时间太长,提交通不过

    2、采用'Sieve of Eratosthenes'方法,该方法的思路是:

    ①质数是除了1和本身外,不被任何数整除,那么任何一个质数的倍数都不会是质数

    ②我们知道最小的质数为2,因此从2开始遍历到n-1。

    ③2的所有倍数都不是质数,所以将2的所有倍数都标记为非质数。

    ④依次遍历下一个元素,下一个标记为质数的元素一定是质数。因为如果该元素是非质数的话,一定能被除了1和本身外的某一个数x整除,即该数是x的整数倍,而x一定是我们曾经遍历过的数;而依据第三步,我们所有遍历过的数的倍数都被标记为非质数了,我们不可能遍历到非质数,因而相互矛盾;综上即该元素一定是质数

    ⑤遍历完成后,能够标记所有的数字是否是质数

    代码:

    class Solution:
        def countPrimes(self, n: int) -> int:
            count,flag = 0,[True]*(n) #1代表质数,0代表非质数
            for i in range(2,n):#从2开始遍历,i代表当前第一个数,i代表这个数所在位置
                if flag[i]:#如果当前位置判定为True的话
                    count += 1
                    for j in range(i*i,n,i):#将该质数的所有倍数都设定为False,即非质数
                        flag[j] = False         
            return count
        

    在循环中尽量不要增加计算,哪怕是加减计算,任何计算量的增加都会增加运行时间,导致提交结果运行时间非常长,结果很差;因而牺牲一点空间,换取时间的大幅缩短也是非常值得的

  • 相关阅读:
    C#磁吸屏幕窗体类库
    准备
    我写的诗
    How to turn off a laptop keyboard
    How to tell which commit a tag points to in Git?
    Why should I care about lightweight vs. annotated tags?
    How to get rid of “would clobber existing tag”
    Facebook, Google and Twitter threaten to leave Hong Kong over privacy law changes
    The need for legislative reform on secrecy orders
    Can a foreign key be NULL and/or duplicate?
  • 原文地址:https://www.cnblogs.com/xiaohua92/p/11155659.html
Copyright © 2020-2023  润新知