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.

难度:easy

题目:统计小于非负整数n的所有素数。

思路:参考素数筛选法。

Runtime: 11 ms, faster than 94.69% of Java online submissions for Count Primes.
Memory Usage: 35.9 MB, less than 21.43% of Java online submissions for Count Primes.

class Solution {
    public int countPrimes(int n) {
        boolean[] notPrimes = new boolean[n];
        int count = 0;
        for (int i = 2; i < n; i++) {
            if (!notPrimes[i]) {
                count++;
                for (int j = 2 * i; j < n; j += i) {
                    notPrimes[j] = true;
                }
            }
        }
        
        return count;
    }
}

linm
1 声望4 粉丝

〜〜〜学习始于模仿,成长得于总结〜〜〜


« 上一篇
275. H-Index II