Leetcode-204. Count Primes
2017-01-01 03:53
211 查看
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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?
这个题目比较郁闷。我是用判断一个数是不是数组,时间复杂度也是O(n * sqrt(n))不知道为什么速度很慢。可能是因为开根号的原因。通用的那个解法我也想过,但是觉得时间复杂度其实差不多,不知道为什么快那么多。。大概明白了,确实还是快一些。Your
runtime beats 64.88% of java submissions.
public class Solution {
public int countPrimes(int n) {
boolean[] notPrime = new boolean
;
int count = 0;
for (int i = 2; i < n; i++) {
if (notPrime[i] == false) {
count++;
for (int j = 2; i*j < n; j++) {
notPrime[i*j] = true;
}
}
}
return count;
}
}
博客链接:mcf171的博客
——————————————————————————————
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?
这个题目比较郁闷。我是用判断一个数是不是数组,时间复杂度也是O(n * sqrt(n))不知道为什么速度很慢。可能是因为开根号的原因。通用的那个解法我也想过,但是觉得时间复杂度其实差不多,不知道为什么快那么多。。大概明白了,确实还是快一些。Your
runtime beats 64.88% of java submissions.
public class Solution {
public int countPrimes(int n) {
boolean[] notPrime = new boolean
;
int count = 0;
for (int i = 2; i < n; i++) {
if (notPrime[i] == false) {
count++;
for (int j = 2; i*j < n; j++) {
notPrime[i*j] = true;
}
}
}
return count;
}
}
相关文章推荐
- [leetcode]: 204. Count Primes
- LeetCode 204. Count Primes
- LeetCode 204. Count Primes
- [LeetCode]--204. Count Primes
- [LeetCode]204. Count Primes
- LeetCode 204. Count Primes
- [LeetCode] 204. Count Primes
- LeetCode 204. Count Primes
- LeetCode 204. Count Primes
- [LeetCode]204. Count Primes
- LeetCode - 204. Count Primes
- leetcode 204. Count Primes
- 【LeetCode】204. Count Primes
- LeetCode 204. Count Primes
- 【LeetCode】204. Count Primes
- LeetCode *** 204. Count Primes
- Leetcode——204. Count Primes
- LeetCode-204. Count Primes
- 【算法作业7】LeetCode 204. Count Primes
- leetcode No204. Count Primes