题目

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?

分析

计算小于n的非负整数中素数的个数。

这本是一个简单的题目,直观的反应,就是逐个判断并累计数目,但是直接这样提交的话得到的肯定是TLE的。因为本题的核心便是考察的性能问题。

素数的动态演示,此处给出了素数累计的另一种思路,我们知道任何一个素数的倍数都是合数,从此出发,先初始化一个n个单元的标志数组,将每个元素标记为素数,然后将素数的倍数标志改为false。最后遍历标志数组,得到素数的个数。

下面给出三种实现,方法一是TLE的算法,方法二和方法三核心思想一样,只不过是采用了不同的累计方式,是AC的。

AC代码

class Solution {
public:
//方法一:逐个判断O(n^(3/2))算法,TLE
int countPrimes1(int n) {
int count = 0;
for (int i = 2; i < n; ++i)
{
if (isPrime(i))
++count;
}
return count;
} bool isPrime(int n)
{
for (int i = 2; i <= sqrt(n); ++i)
if (n % i == 0)
return false;
return true;
} //方法二:素数不能被比它小的整数整除,建一个标志数组,从2开始,把其倍数小于N的都删掉
int countPrimes2(int n)
{
vector<int> flags(n + 1, 1);
for (int i = 2; i*i <= n; ++i)
{
//把素数的倍数全部设置为非素数标志
if (flags[i])
{
//内层循环从i开始, 比i小的会在以前就被check过
for (int j = i; i*j < n; ++j)
{
flags[i*j] = 0;
}//for
}//for
}//for int count = 0;
for (int i = 2; i < n; ++i)
{
if (flags[i])
++count;
}
return count;
} //方法三,与二思路相同,另一种实现方式
int countPrimes(int n)
{
if (n <= 2)
return 0; vector<int> flags(n, 1);
//记录素数的个数
int count = n - 2;
for (int i = 2; i*i <= n; ++i)
{
if (flags[i])
{
//内层循环从i开始, 比i小的会在以前就被check过
for (int j = i; i*j < n; ++j)
{
//如果原来标记的为素数,现在改为非素数,同时更新素数个数
if (flags[i*j])
{
flags[i*j] = 0;
--count;
}//if
}//for
}//if
}//for
return count;
}
};

GitHub测试程序源码

Leetcode(204) Count Primes的更多相关文章

  1. Leetcode(59)-Count Primes

    题目: Description: Count the number of prime numbers less than a non-negative number, n. 思路: 题意:求小于给定非 ...

  2. LeetCode(38) Count and Say

    题目 The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111 ...

  3. Leetcode(5)最长回文子串

    Leetcode(4)寻找两个有序数组的中位数 [题目表述]: 给定一个字符串 s,找到 s 中 最长 的回文子串.你可以假设 s 的最大长度为 1000.' 第一种方法:未完成:利用回文子串的特点 ...

  4. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  5. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  6. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  7. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

  8. LeetCode(116) Populating Next Right Pointers in Each Node

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  9. LeetCode(113) Path Sum II

    题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...

随机推荐

  1. NetCore1.1+Linux

    NetCore1.1+Linux部署初体验   1.环境准备 Centaos7+Win10 虚拟机 Win10安装VS2017 https://www.asp.net/downloads注意勾选下.N ...

  2. 《javascript设计模式》笔记之第十二章:装饰者模式

    一.装饰者模式的作用 为函数或者对象的方法添加一些行为.     二.装饰者模式的原理 装饰者模式不是直接修改对象,而是以要修改的对象为基础,新建一个对象.不过这个新建的对象看起来就像在原对象的基础上 ...

  3. java中接口(interface)和虚基类(abstract class)的区别

    在Java语言中,abstract class和interface是支持抽象类定义的两种机制.正是由于这两种机制的存在,才赋予了Java强大的面向对象能力.abstract class和interfa ...

  4. BZOJ4939: [Ynoi2016]掉进兔子洞(莫队 bitset)

    题意 题目链接 一个长为 n 的序列 a. 有 m 个询问,每次询问三个区间,把三个区间中同时出现的数一个一个删掉,问最后三个区间剩下的数的个数和,询问独立. 注意这里删掉指的是一个一个删,不是把等于 ...

  5. SQL SERVER 2014 缺少Business Intelligence 解决办法

    SQL SERVER 2014安装完所有的数据库工具后,缺少开发工具 Business Intelligence   之解决办法. https://msdn.microsoft.com/en-us/l ...

  6. Android中当item数量超过一定大小RecyclerView高度固定

    Android中当item数量超过一定大小时,将RecyclerView高度固定 方法1 直接通过LayoutParams来设定相应高度 ViewGroup.LayoutParams lp = rv. ...

  7. 读写属性/if判断那点事/数组

    读写属性属性操作注意事项 js中不允许出现"-".所以font-size变成fontSize/margin-top变成marginTop. Op.style.with=" ...

  8. LR使用流程简介之录制方式说明

    1.LR脚本录制方式说明1)HTML-based script基于HTML的脚本 从内存中读取并下载资源,较少的关联处理,可以加入图片检查,回放时需要解析返回的信息 a-基于用户行为的方式 web_l ...

  9. App测试流程及测试点

    1 APP测试基本流程 1.1流程图 接收版本 尽快申请到正式环境下测试 不符 App测试版本送测规范 用户行为统计测试 后台订单统计测试 尽快申请到正式环境下测试 兼容性测试.性能压力测试 功能测试 ...

  10. sudo的用法

    为了系统安全我们一般不直接使用root用户进行日常维护,sudo是临时提升root权限,有时执行一些命令或者更新没权限的文件时需要使用root,这个时候就需要sudo上场了 普通用户是没有sudo使用 ...