Leetcode 401~420
作者:互联网
412. Fizz Buzz
知识点: 列表 list append % 求模运算(余数)
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
res = []
for i in range(1, n+1):
# if not i%15:
# tmp = "FizzBuzz"
# elif not i%3:
# tmp = "Fizz"
# elif not i%5:
# tmp = "Buzz"
# else:
# tmp = str(i)
tmp = ""
if not i%3:
tmp += "Fizz"
if not i%5:
tmp += "Buzz"
if not tmp:
tmp = str(i)
res.append(tmp)
return res
# return ["Fizz"[i%3*4:] + "Buzz"[i%5*4:] or str(i) for i in range(1,n+1)]
414. 第三大的数
知识点: 条件语句 if elif else 条件表达式 one if … else two
class Solution:
def thirdMax(self, nums: List[int]) -> int:
x = y = z = -inf
for n in nums:
# 方法一
# if n > x:
# x, n = n, x # 替换出 x
# if x > n > y:
# y, n = n, y
# if y > n > z:
# z = n
# 方法二
if n > x:
z, y, x = y, x, n # 依次替换
elif x > n > y:
z, y = y, n
elif y > n > z:
z = n
return x if z == -inf else z
列表(list) 集合(set) 字典(dict) 排序(sorted,sort)
class Solution:
def thirdMax(self, nums: List[int]) -> int:
d = {}
for n in nums:
d[n] = d.get(n, 0) + 1
return max(d) if len(d) < 3 else sorted(d)[-3]
# return x[-3] if len(x:=sorted(list(set(nums)))) > 2 else max(x)
标签:tmp,elif,return,int,else,401,420,i%,Leetcode 来源: https://blog.csdn.net/weixin_43955170/article/details/121077848