描述
Count the number of prime numbers less than a non-negative number, n.
您在真实的面试中是否遇到过这个题?
和第792题思路相同
class Solution { public: /** * @param n: a integer * @return: return a integer */ int countPrimes(int n) { // write your code here int count = n-1; bool *flag = new bool[n]; for (int i = 0; i < n; ++i) flag[i] = true; for (int i = 2; i <= sqrt(n); ++i) { for (int j = i * i; j < n; j += i) { if (true == flag[j]) { flag[j] = false; --count; } } } delete flag; flag = nullptr; return count - 1; } };