LeetCode C++ 204. Count Primes【Math/Hash Table】簡單
Count the number of prime numbers less than a non-negative number, n
.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
Constraints: 0 <= n <= 5 * 10^6
題意:統計所有小於非負整數 n
的質數的數量。
解法 埃利特斯拉篩法
普通的埃式篩法:
class Solution {
public:
int countPrimes(int n) { //埃利特斯拉篩法
if (n <= 1) return 0;
int cnt = 0;
const int maxn = 5 * 1e6;
bitset<maxn> bst;
for (int i = 2; i < n; ++i) {
if (bst[i] == 0) {
++cnt;
for (int j = i + i; j < n; j += i) bst[j] = 1;
}
}
return cnt;
}
};
執行效率如下:
執行用時:184 ms, 在所有 C++ 提交中擊敗了69.29% 的使用者
記憶體消耗:7 MB, 在所有 C++ 提交中擊敗了32.00% 的使用者
優化的埃式篩法:
class Solution {
public:
int countPrimes(int n) {
if (n <= 1) return 0;
int cnt = 0;
const int maxn = 5 * 1e6;
bitset<maxn> bst;
for (int i = 2; i * i < n; ++i)
if (bst[i] == 0)
for (int j = i * i; j < n; j += i) bst[j] = 1;
for (int i = 2; i < n; ++i)
if (bst[i] == false) ++cnt;
return cnt;
}
};
執行效率如下:
執行用時:164 ms, 在所有 C++ 提交中擊敗了70.36% 的使用者
記憶體消耗:6.9 MB, 在所有 C++ 提交中擊敗了32.18% 的使用者
相關文章
- 204. Count Primes
- LeetCode C++ 387. First Unique Character in a String【String/Hash Table】簡單LeetCodeC++
- LeetCode C++ 441. Arranging Coins【Math/Binary Search】簡單LeetCodeC++
- [LintCode/LeetCode] Check Sum of K PrimesLeetCode
- HashMap、Hash Table、ConcurrentHashMapHashMap
- Leetcode 38 Count and SayLeetCode
- C語言實現一個簡易的Hash table(7)C語言
- LeetCode C++ 703. Kth Largest Element in a Stream【Heap/Design】簡單LeetCodeC++
- LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單LeetCodeC++
- [LeetCode] 811. Subdomain Visit CountLeetCodeAI
- 【Leetcode】1395. Count Number of TeamsLeetCode
- [20181226]簡單探究cluster table.txt
- Azure Table Storage(一) : 簡單介紹
- C++簡單vectorC++
- [LeetCode] 2257. Count Unguarded Cells in the GridLeetCode
- 【LeetCode】簡單題目集LeetCode
- 「LeetCode By Python」簡單篇(一)LeetCodePython
- table表單製作個人簡歷
- leetcode 127. 單詞接龍(C++)LeetCodeC++
- LeetCode #1:Two Sum(簡單題)LeetCode
- LeetCode 1 兩數之和(簡單)LeetCode
- el-table 的 el-table-column 的key使用Math.random() 篩選列random
- C++ - 簡單工廠模式C++模式
- [LeetCode] 2960. Count Tested Devices After Test OperationsLeetCodedev
- [LeetCode] 3184. Count Pairs That Form a Complete Day ILeetCodeAIORM
- 【Leetcode】1180. Count Substrings with Only One Distinct LetterLeetCode
- leetcode 283. 移動零(簡單)LeetCode
- [20180129]簡單探究cluster table(補充)4.txt
- [20181229]簡單探究cluster table(補充)3.txt
- [20181227]簡單探究cluster table(補充)2.txt
- vxe-form table 表單實現簡歷模板ORM
- C++ :引用計數(reference count) 實現C++
- C++中const的簡單用法C++
- c++簡單程式設計-3C++程式設計
- C++基礎簡單總結C++
- 簡單C++執行緒池C++執行緒
- flinkSql join redis的hash結構維表簡單實現SQLRedis
- leetCode資料查詢筆記(簡單)LeetCode筆記