LeetCode 204. Count Primes--从一开始的质数个数--Python解法--面试算法题

该博客主要介绍了LeetCode 204题目的解决方案,通过Python实现筛法(Sieve of Eratosthenes)在O(n log log n)的时间复杂度内计算小于n的质数数量。博主分享了自己在面试中对时间复杂度回答失误的经历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:Count Primes - LeetCode


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.

这道题目是算有多少个质数在一个范围内,做法不难。

但穷举的解法会超时。

比较好的做法是Sieve of EratosthenesSieve of Eratosthenes - Wikipedia

时间复杂度为 O(n log log n),空间复杂度为 O(n)

我之前在面试的时候时间复杂度没回答正确。。。。

Python解法如下:

class Solution:
    def countPrimes(self, n: int) -> int:
        if n < 3:
            return 0
        primes = [True]*n
        primes[0], primes[1] = False,False
        for i in range(2, int(n ** 0.5) + 1):
            if primes[i]:
                for j in range(i*i,n,i):
                    primes[j]=False
        return sum(primes)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值