【算法与数据结构相关】【LeetCode】【204 计数质数】【Python】

题目:统计所有小于非负整数 的质数的数量。

示例:

输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。

思路:1、从数字2开始,将所有其整数倍从小于n的数中排除,然后依次排除3的倍数、(4已经被排除)、5的倍数....最终剩下的就是小于n的所有质数

代码:

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 2:
            return 0
        else:
            result = [i for i in range(2,n)]
            for item in result:
                k = 2
                while item*k < n:
                    if item*k in result:
                        result.remove(item*k)
                    k += 1
            return len(result)

运行结果:超出时间限制!!!这么优秀的算法还超出时间限制!!!

看了别人的代码,思路是没问题的,但是实现方式不一样:我是通过list.remove来移除元素,而remove操作较为耗时,参考别人的做法:维护一个数组,数组中的元素为1或0来表示当前位置的索引是否为素数。

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 2:
            return 0
        else:
            result = [1]*n
            result[0] = result[1] = 0
            for i in range(n):
                if result[i]:
                    result[2*i:n:i] = [0]*len(result[2*i:n:i])
            return sum(result)

猜你喜欢

转载自blog.csdn.net/gq930901/article/details/81914980