204、计算质数
统计所有小于非负整数 n 的质数的数量。
示例:
输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7
Solution: 可以建立一个大小为n的布尔类型的list,从0开始,设置0,1为False[即非素数],2置为True,且将小于n的2的倍数均置为FALSE,之后同理,最终True的个数即为素数的个数。
#暴力搜索
class Solution:
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
res = []
for i in range(2, n):
if self.isPrime(i):
res.append(i)
return len(res)
def isPrime(self, n):
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(pow(n, 0.5)) + 1):
if n % i == 0:
return False
return True
solution = Solution()
print(solution.countPrimes(20))
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 1:
return 0
nums = [None] * n
nums[0], nums[1] = False, False
for i in range(n):
if nums[i] == None:
nums[i] = True
for j in range(i + i, n, i):
nums[j] = False
return sum(nums)
solution = Solution()
print(solution.countPrimes(4))
453、分饼干
假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
示例 1:
输入: [1,2,3], [1,1]
输出: 1
解释:
你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。所以你应该输出1。
示例 2:
输入: [1,2], [1,2,3]
输出: 2
解释:
你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
你拥有的饼干数量和尺寸都足以让所有孩子满足。
所以你应该输出2.
Solution: 为了防止大饼干用来满足了小胃口的孩子,所以先对两个数组进行排序。然后对孩子数组进行遍历,当孩子的胃口大于等于饼干尺寸时,result加1,且将这块饼干移出数组,最后返回result
class Solution(object):
def findContentChildren(self, w, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
w = sorted(w)
s = sorted(s)
result = 0
for i in range(len(w)):
for j in range(len(s)):
if w[i] <= s[j]:
s.remove(s[j])
result += 1
break
return result
solution = Solution()
print(solution.findContentChildren([8,19, 2,2, 4], [3, 3]))
#方法二
class Solution(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g, s = sorted(g), sorted(s)
result = 0
if not s:
return result
for each_g in g:
for each_s in s:
if each_g <= each_s:
result += 1
s.remove(each_s)
break
if not s:
break
return result
# 方法三
class Solution(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g, s = sorted(g), sorted(s)
result = 0
i, j = 0, 0
if not s:
return result
while i < len(g) and j < len(s):
if g[i] <= s[j]:
result += 1
i += 1
j += 1
return result