204 Count Primes
来源:互联网 发布:淘宝五钻店铺多少钱 编辑:程序博客网 时间:2024/05/08 09:44
题目链接:https://leetcode.com/problems/count-primes/
题目:
Description:Count the number of prime numbers less than a non-negative number, n.Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.Hint:Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?
解题思路:
厄拉多塞筛法
每找到一个素数,就将其倍数抹去。最终留下的都是素数。
参考链接:https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
在代码中,先创建一个长度为 n 的数组(数组为布尔类型),将数组元素全部赋值为 true。从下标为2开始遍历数组,若元素值为 true,count 加一,并将数组下标为其下标倍数的元素赋值为 false;若元素为 false,就跳出本次循环。
注意:
用 ArrayList 来存储,会超时!
public class Solution { public int countPrimes(int n) { int count = 0; boolean[] buf = new boolean[n]; for(int i = 0; i < n; i ++) buf[i] = true; for(int i = 2; i < n; i ++) { if(buf[i] == false) continue; for(int j = i + i; j < n; j = j + i) buf[j] = false; count ++; } return count; }}
20 / 20 test cases passed.Status: AcceptedRuntime: 288 ms
0 0
- LeetCode 204 - Count Primes
- LeetCode 204-Count Primes
- [LeetCode 204] Count Primes
- leetcode 204: Count Primes
- LeetCode 204:Count Primes
- 204 Count Primes
- leetcode-204 Count Primes
- Count Primes - LeetCode 204
- Leetcode 204 Count Primes
- leetcode[204]:Count Primes
- Leetcode 204 Count Primes
- leetcode-204 Count Primes
- leetcode 204:Count Primes
- 204Count Primes
- leetcode-204-Count Primes
- 204 Count Primes
- leetCode #204 Count Primes
- leetcode 204: Count Primes
- 【连载】实用小demo连载 1 —— 页码切换demo
- THINKPHP 数据库查询where语句条件
- memcached缓存系统学习笔记之一:memcached缓存系统基础知识和环境搭建
- 如何提高软件安全性检测效率(中)
- UITarget-Action(定义一个触碰屏幕启动功能的方法)
- 204 Count Primes
- HDU 4312 最小切比雪夫距离-转化成曼哈顿距离再分治
- hibernate自定义主键生成策略
- MFC程序最小化到系统托盘
- iOS应用的crash日志的分析基础
- Github远程协作
- log4j + 实战应用分析
- 动态规划
- js动态移除DIV