python 2024-10
第七课
204. 计数质数
语法:while else,continue break 埃氏筛 数的倍数不是素数。
class Solution:
def countPrimes(self, n: int) -> int:
res = 0
for i in range(2, n):
for j in range(2, i):
if i % j == 0:
break
else:
res += 1
return res
优化
class Solution:
def countPrimes(self, n: int) -> int:
num_list = [1] * n
res = 0
for i in range(2, n):
if not num_list[i]: continue
res += 1
for j in range(2 * i, n, i):
num_list[j] = 0
return res
263. 丑数
class Solution:
def isUgly(self, n: int) -> bool:
if n <= 0: return False
factors = [2, 3, 5]
for fac in factors:
while n % fac == 0:
n //= fac
return n == 1
第八课
412. Fizz Buzz
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
res = [''] * 列表包含 n # n 个 空串
# res = []
for i in range(1, n + 1):
if i % 15 == 0: x = "FizzBuzz" # 先处理 15 的倍数
elif i % 3 == 0: x = "Fizz"
elif i % 5 == 0: x = "Buzz"
else: x = str(i) # 转换成字符串
res[i - 1] = x
# res.append(x)
return res
# return ['Fizz'[i%3*4:]+"Buzz"[i%5*4:] or str(i) for i in range(1, n+1)]
2239. 找到最接近 0 的数字
class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
ans = inf
for x in nums:
if abs(x) == abs(ans): ans = max(x, ans)
elif abs(x) < abs(ans): ans = x
return ans
3289. 数字小镇中的捣蛋鬼
标记法
class Solution:
def getSneakyNumbers(self, nums: List[int]) -> List[int]:
res = [0, 0]
n = len(nums)
i = 0
for x in nums:
x %= n
if nums[x] >= n:
res[i] = x
i += 1
if i == 2: break
nums[x] += n
return res
2432… 处理用时最长的那个任务的员工
class Solution:
def hardestWorker(self, n: int, logs: List[List[int]]) -> int:
ans = pre = most = 0
for i, t in logs:
dif = t - pre
pre = t
if most < dif or most == dif and ans > i:
ans = i
most = dif
return ans