1 题目

Description:

Count the number of prime numbers less than a non-negative number, n.

接口:public int countPrimes(int n);

2 思路

统计小于n的素数个数,注意不包括n。

思路1:素数的判断

很容易想到素数的判断isPrime,然后逐个数来进行判断是否是素数。进行统计,输出结果。

复杂度: 把isPrime时间复杂度控制在O(n^0.5)的话,因此:Time:O(n^1.5) , Space:O(1)。

提交代码仍然超时。

思路2: 素数表

素数表的产生,在[1 to n)的范围内,标记出 非素数,剩下的就是素数了。

思路:

  1. 初始化所有的[2,n)都是素数
  2. 剔除掉 非素数
  3. 统计素数个数

如何标记 非素数呢?分组标记:

  • 2,[4,6,8,10,12,14,16,18,20,22,24...];
  • 3,[9,12,15,18,21,24,27,...];
  • 5,[25,30,35...]
  • 考虑一下终止条件

复杂度: Time: O(n log log n) , Space: O(n)

3 代码

思路1

	// 判断一个数是否是素数的方法:不是最好,但还可以。素数表是判断素数的好方法。
// Time:O(sqrt(n)) Space:O(1)
boolean isPrime(int n) {
for (int i = 2; (i * i) <= n; i++) {
if (n % i == 0)
return false;
}
return true;
} /**
* Solution 1: 逐个判断是否是素数,思路简单。但是超时
* Time:O(n^1.5) Space:O(1)
*/
public int countPrimes(int n) {
int count = 0;
for (int i = 2; i <= n; i++) {
if(isPrime(i)) count++;
}
return count;
}

思路2

	// Time: O(n log log n) Space: O(n)
public int countPrimes(int n) {
// 初始化所有的都是素数,在剔除掉 `非素数`
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++) {
isPrime[i] = true;
} // 剔除非素数
for (int i = 2; (i * i) < n; i++){
if (isPrime[i]) {
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
} // 统计素数个数
int count = 0;
for (boolean is : isPrime) {
if (is) count++;
}
return count;
}

4 总结

素数是比较经典的题目。此题的tag: HashTable, Math

5 参考

leetcode面试准备: CountPrimes的更多相关文章

  1. leetcode面试准备: Maximal Rectangle

    leetcode面试准备: Maximal Rectangle 1 题目 Given a 2D binary matrix filled with 0's and 1's, find the larg ...

  2. leetcode面试准备: Game of Life

    leetcode面试准备: Game of Life 1 题目 According to the Wikipedia's article: "The Game of Life, also k ...

  3. leetcode面试准备: Word Pattern

    leetcode面试准备: Word Pattern 1 题目 Given a pattern and a string str, find if str follows the same patte ...

  4. leetcode面试准备:Add and Search Word - Data structure design

    leetcode面试准备:Add and Search Word - Data structure design 1 题目 Design a data structure that supports ...

  5. leetcode面试准备:Reverse Words in a String

    leetcode面试准备:Reverse Words in a String 1 题目 Given an input string, reverse the string word by word. ...

  6. leetcode面试准备:Implement Trie (Prefix Tree)

    leetcode面试准备:Implement Trie (Prefix Tree) 1 题目 Implement a trie withinsert, search, and startsWith m ...

  7. leetcode面试准备:Triangle

    leetcode面试准备:Triangle 1 题目 Given a triangle, find the minimum path sum from top to bottom. Each step ...

  8. leetcode面试准备:Sliding Window Maximum

    leetcode面试准备:Sliding Window Maximum 1 题目 Given an array nums, there is a sliding window of size k wh ...

  9. leetcode面试准备:Simplify Path

    leetcode面试准备:Simplify Path 1 题目 Given an absolute path for a file (Unix-style), simplify it. For exa ...

随机推荐

  1. 初见Javascript

    1.HTML 中的脚本必须位于 <script> 与 </script> 标签之间. 脚本可被放置在 HTML 页面的 <body> 和 <head> ...

  2. jqery选择器

    根据可见性 属性 匹配元素 <!doctype html> <html lang="en"> <head> <meta charset=& ...

  3. SQL 有父标识的 递归查询

    递归查询,临时表的高级应用 WITH temp AS ( --父项 SELECT * FROM Ar_Area WHERE Ar_Parent = UNION ALL --递归结果集中的下级 SELE ...

  4. linux下apache-tomcat的安装

    一.JDK安装 1.安装JDK软件包 本例使用的JDK安装包为jdk-6u19-linux-x64.bin,该包是一个编译好的二进制可执行程序包,只需要执行即可安装. 首先进入存放JDK安装包的目录( ...

  5. IOS-开发日志-UIScrollView

    UIScrollView 1.  contentOffset 默认CGPointZero,用来设置scrollView的滚动偏移量. // 设置scrollView的滚动偏移量 scrollView. ...

  6. 10.12_win8风格,把专业书籍当小说看,SQLite

    (1)CSS:Metro UI CSS(Metroui) 是一套实现了 Windows 8 的 Metro 风格界面的 CSS 框架..官网.BootMetro . (2)[开源访谈]CecOS作者 ...

  7. 给python类动态添加方法(method)

    群里有人问如何做到 def foo(): pass class Bar(object): pass Bar.set_instance_method(foo) b = Bar() b.foo() 这个其 ...

  8. OpenJudge 2790 迷宫

    1.链接地址: http://bailian.openjudge.cn/practice/2790/ 2.题目: 总时间限制: 3000ms 内存限制: 65536kB 描述 一天Extense在森林 ...

  9. greenlet代码解读

    协程 上次已经讲解了协程的的实现方法,和我对协程的一些理解.这里指我就先以代码说明协程的运行.def test1():    print 12         (2)    gr2.switch()  ...

  10. 代码笔记-触摸事件插件hammer.js使用

    如果要使用jquery,则需要下载jquery.hammer.min.js版本 新建一个hammer对象生成的对象是dom对象,不能直接使用jqeury 的  $(this)方法,需要先将其转成jqu ...