LeetCode中Count Primes的java实现
2015-05-22 10:40
375 查看
题目如下:
Description:
Count the number of prime numbers less than a non-negative number, n.
一开始用的方法入下,结果运算时间太大
public class Solution {
public int countPrimes(int n) {
boolean mark = true;
int count=0;
for(int i=2;i<n;i++)
{
for(int m=2; m<=Math.sqrt(i);m++ )
{
mark = true;
if(i%m==0)
{
mark =false;
break;
}
}
if(mark)
{
count++;
}
}
return count;
}
}
后来改成如下写法,通过
public class Solution {
public int countPrimes1(int n)
{
boolean bool[] = new boolean
;
if (n <= 2) return 0;
int counter = n-2;
int j = 0;
for (int i = 2; i <= Math.floor(Math.sqrt(n)); i++) {
j = i + i;
if (!bool[i])
{
while (j < n) {
if (!bool[j]) {
bool[j] = true;
counter --;
}
j = j + i;
}
}
}
return counter;
}
Description:
Count the number of prime numbers less than a non-negative number, n.
一开始用的方法入下,结果运算时间太大
public class Solution {
public int countPrimes(int n) {
boolean mark = true;
int count=0;
for(int i=2;i<n;i++)
{
for(int m=2; m<=Math.sqrt(i);m++ )
{
mark = true;
if(i%m==0)
{
mark =false;
break;
}
}
if(mark)
{
count++;
}
}
return count;
}
}
后来改成如下写法,通过
public class Solution {
public int countPrimes1(int n)
{
boolean bool[] = new boolean
;
if (n <= 2) return 0;
int counter = n-2;
int j = 0;
for (int i = 2; i <= Math.floor(Math.sqrt(n)); i++) {
j = i + i;
if (!bool[i])
{
while (j < n) {
if (!bool[j]) {
bool[j] = true;
counter --;
}
j = j + i;
}
}
}
return counter;
}
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【204-Count Primes(统计质数)】
- Java [Leetcode 204]Count Primes
- Count Primes Leetcode JAVA
- Java for LeetCode 204 Count Primes
- 【LeetCode-面试算法经典-Java实现】【038-Count and Say(计数和表述)】
- Leetcode-204(Java) Count Primes
- [LeetCode] Count Primes(Java)
- LeetCode 204 Count Primes题解
- leetcode--Count Primes
- java8实现spark wordcount并且按照value排序输出
- [LeetCode]Count Primes
- java8实现spark streaming的wordcount
- Java源码 Integer.bitCount实现过程
- [Leetcode] Count Primes
- 【LeetCode】475. Heaters (java实现)
- LeetCode1 TwoSum (java实现)
- 【LeetCode】475. Heaters (java实现)
- leetcode15 3Sum(java 实现)
- leetcode16 3Sum Closest(java实现)
- 【leetcode】102. Binary Tree Level Order Traversal【java】使用队列实现层序遍历