204 Count Primes
2015-08-03 17:58
267 查看
题目链接:https://leetcode.com/problems/count-primes/
题目:
解题思路:
厄拉多塞筛法
每找到一个素数,就将其倍数抹去。最终留下的都是素数。
参考链接:https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
在代码中,先创建一个长度为 n 的数组(数组为布尔类型),将数组元素全部赋值为 true。从下标为2开始遍历数组,若元素值为 true,count 加一,并将数组下标为其下标倍数的元素赋值为 false;若元素为 false,就跳出本次循环。
注意:
用 ArrayList 来存储,会超时!
题目:
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 ; 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: Accepted Runtime: 288 ms
相关文章推荐
- jQuery验证控件jquery.validate.js使用说明+中文API
- SupportV7包中 SwipeRefreshLayout 修改下拉控件的距离
- js动态移除DIV
- 【工具】创建GitHub代码库(MyGit最基本的使用)
- android退出机制方法
- 杭电-1009
- log4j + 实战应用分析
- PHPCMS中调用自定义BOX值与选项方法
- 如何提高软件安全性检测效率(中)
- 第一个Python小程序
- MFC程序最小化到系统托盘
- python爬虫 豆瓣电影
- onMeasure流程解析
- USB通信协议——深入理解
- J - Fire!---UVA 11624
- struts2 日期类型自动转换类型
- 动态规划
- 背包问题九讲
- Github远程协作
- iOS应用的crash日志的分析基础