題目:
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i (as a string) if none of the above conditions are true.
給定一數n,返回一個由字串組成的陣列,規則如下:
若x可被3和5整除,陣列第x個元素為"FizzBuzz"
若x僅可被3整除,陣列第x個元素為"Fizz"
若x僅可被5整除,陣列第x個元素為"Buzz"
若x不可被3和5整除,陣列第x個元素為x的字串型態
ex:input:15=>output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
我們對1~n的數(i)全部進行判斷
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans=[]
for i in range(1,n+1):
temp=''
if i % 3==0:
temp=temp+"Fizz"
if i % 5==0:
temp=temp+"Buzz"
if temp=='':
ans.append(str(i))
else:
ans.append(temp)
return ans
每次判斷都設立一個空字串(temp)
若i可被3整除,在temp尾端加上"Fizz"
若i可被5整除,在temp尾端加上"Buzz"
要是temp經判斷完是空字串,則於要回傳的陣列(ans)append i的字串型態
反之則直接append temp
最後執行時間42ms(faster than 95.59%)
那我們下題見
x = [ 'Fizz' * (n % 3 == 0) + 'Buzz' * (n % 5 == 0) or str(n) for n in range(1,46) ]
print(x)
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz', '16', '17', 'Fizz', '19', 'Buzz', 'Fizz', '22', '23', 'Fizz', 'Buzz', '26', 'Fizz', '28', '29', 'FizzBuzz', '31', '32', 'Fizz', '34', 'Buzz', 'Fizz', '37', '38', 'Fizz', 'Buzz', '41', 'Fizz', '43', '44', 'FizzBuzz']
有料ㄟ,這就是所謂的one-linear solution吧
當時看discussion也蠻多大神用一行解的
我是沒有特別挑戰啦XD
只要和最佳解時間複雜度一樣我就滿足了