码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode-204(Java) Count Primes

时间:2015-08-05 10:27:34      阅读:366      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

 

传送门:https://leetcode.com/problems/count-primes/

 

尽可能把查找次数缩小,直接用双重for会超时。

public class Solution {
    public int countPrimes(int n)
    {
        //默认全为false
        boolean res[] = new boolean[n];
        for(int i = 2; i * i < n; i++)
        {
            if(!res[i]){
                //直接找到相乘小与n的数,说明不是素数
                for(int j = i; i * j < n; j++){
                    res[i * j] = true;
                }
            }
        }
        int count = 0;
        for(int i = 2; i < n; i++)
            if(res[i] == false)
                count++;
        return count;
    }
}

 

Leetcode-204(Java) Count Primes

标签:

原文地址:http://www.cnblogs.com/zetrov/p/4703909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!