LeetCode - 解题笔记 - 204 - Count Primes

Solution 1

这个题是我栽过坑的,一定要好好学习!

最简单的枚举方法,根据给定的数字从2一直枚举判定。

但是判定这里不需要也不能试遍所有数字(2次复杂度,会TLE),可以将这个范围缩小到 n \sqrt n n ,这样就可以了。

但是目前这个方法因为题目范围修改已经被判定TLE了,因此只能进一步优化了

  • 时间复杂度: O ( n n ) O(n \sqrt n) O(nn ),其中 n n n为输入的数字,枚举和判定
  • 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个状态量
class Solution {
public:
    int countPrimes(int n) {
        int ans = 0;
        
        // 逐个枚举判定
        for (int i = 2; i < n; i++) {
            if (checkPrime(i)) { ans++; }
        }
        
        return ans;
    }
    
private:
    bool checkPrime(int x) {
        for (int i = 2; i * i <= x; i++) {
            if (x % i == 0) { return false; }
        }
        
        return true;
    }
};

Solution 2

埃氏(Eratosthenes)筛,基于观察:当 x x x为质数,其任意多倍数 a x ax ax必为合数,预先标记尽可能多的数字,以减少实际判定质数的次数。同时我们可以继续优化,从 x 2 x^2 x2开始标记以尽可能减少标记的次数,因此其更小的倍数 a x ax ax已经会在 a a a的标记轮次中被标记到。

此外,对埃氏筛还有进一步优化的线性筛,这个等以后有用的时候再进一步学习了。

  • 时间复杂度: O ( n log ⁡ log ⁡ n ) O(n\log \log n) O(nloglogn),其中 n n n为输入的数字,这个结果需要复杂证明,故略,同时可以看到明显比枚举小
  • 空间复杂度: O ( n ) O(n) O(n),其中 n n n为输入的数字,典型的时间换空间的案例
class Solution {
public:
    int countPrimes(int n) {
        int ans = 0;
        
        // 埃氏筛
        vector<bool> isPrime(n, true);
        
        for (int i = 2; i < n; i++) {
            if (isPrime[i]) {
                ans++;
                if ((long long) i * i < n) {
                    for (int j = i * i; j < n; j += i) {
                        isPrime[j] = false;
                    }
                }
            }
        }
        
        return ans;
    }
};

Solution 4

Solution 2的Python实现

class Solution:
    def countPrimes(self, n: int) -> int:
        ans = 0
        
        isPrime = [True] * n
        
        for i in range(2, n):
            if isPrime[i]:
                ans += 1
                if i ** 2 < n:
                    for j in range(i**2, n, i):
                        isPrime[j] = False
        
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值