package LeetCode_HashTable; /** * 题目: * 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 */ public class CountPrimes_204_1023 { public int CountPrimes(int n){ if (n == 0 || n == 1) { return n; } int result = 0; boolean[] notPrime = new boolean[n]; //创建一个长度为n的数组,并将其初始化为false for (int i = 2; i < n; i++) { if (notPrime[i] == false) { result++; //如果notPrime[i]为false,则其为素数,将result加1 } for (int j = i; i * j < n; j++) { notPrime[i * j] = true; } } return result; } }
leetcode:(204) Count Primes(java)
最新推荐文章于 2022-03-16 22:27:52 发布