leetcode python3 简单题204. Count Primes

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第二百零四题

(1)题目
英文:
Count the number of prime numbers less than a non-negative number, n.

中文:
统计所有小于非负整数 n 的质数的数量。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element

(2)解法
① 埃拉托斯特尼筛法
(耗时:2928ms,内存:25.3M)

class Solution:
    def countPrimes(self, n: int) -> int:
        isPrimes = [1] * n
        res = 0
        for i in range(2, n):
            if isPrimes[i] == 1: res += 1
            j = i
            while i * j < n:
                isPrimes[i * j] = 0
                j += 1
        return res

注意:
1.算法的关键就是:比如对于2,找出所有范围内的能被2整除的数,筛掉,再看3,5…以此类推(因为4已经被筛掉了哦)。

② 优化版
(耗时:176ms,内存:37M)

class Solution:
    def countPrimes(self, n: int) -> int:
        if n < 2: return 0
        isPrimes = [1] * n
        isPrimes[0] = isPrimes[1] = 0
        for i in range(2, int(n ** 0.5) + 1):
            if isPrimes[i] == 1:
                isPrimes[i * i: n: i] = [0] * len(isPrimes[i * i: n: i])
        return sum(isPrimes)

猜你喜欢

转载自blog.csdn.net/qq_37285386/article/details/105950070