leetcode-204. 計數質數刷題筆記(c++)

寫在前面

  • 練手題,
  • 回憶知識點

題目詳情

統計所有小於非負整數 n 的質數的數量。

示例:

	輸入: 10
	輸出: 4
	解釋: 小於 10 的質數一共有 4, 它們是 2, 3, 5, 7

ac代碼

  • 時間換空間
    • 逐個判斷是否非質
class Solution
{
public:
    int countPrimes(int n)
    {
        int cnt = 0;
        for(int i=2; i<n; i++)
            if(isPrime(i))
                cnt++;
        return cnt;
    }

    bool isPrime(int n)
    {
        if(n==2 || n==3)
            return true;
        for(int i=2; i*i<=n; i++)
            if(n%i==0)
                return false;
        return true;
    }
};
  • 空間換時間
    • 判斷非質數組,統一計數
      • vector<int>數組初始化
      • count(res.begin(), res.end(), 1) 計算數組中目標值個數
        • 剔除2、3、5、7...以後的倍數
class Solution {
public:
    int countPrimes(int n) {
        if(n < 3) return 0;
        vector<int> res(n, 1);
        res[0] = 0;
        res[1] = 0;
        for(int i = 2; i < sqrt(n); ++i){
            if(res[i] != 1)
                continue;
            for(int j = i*2; j < n; j += i){
                res[j] = 0;
            }
        }
        int num = count(res.begin(), res.end(), 1);
        return num;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章