605.种花问题
今天totally是自己想出来的偏方,所以记一下
题目在这里
第一步,处理特殊情况,先把n=0的情况排除在外,判断n=0直接返回TRUE
第二步,预处理数组,我的想法是扩充数组,把头和尾各加上一个0,这样就方便后续直接扫描整个数组去进行判断,而不用再考虑头尾的情况。
第三步,对扩充的数组进行扫描,扫描的位置是[1,length-1],也就是说不用扫到头和尾,判断i
位置的左右是否为0以及i
位置是0就ok了
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
#左右扩充一格数组,判断原数组左右是否为0即可
if n == 0:
return True
flowerbed_copy = flowerbed
flowerbed_copy.insert(0,0)
flowerbed_copy.append(0)
#print(flowerbed_copy)
length = len(flowerbed)
for i in range(1,length-1):
#print(flowerbed_copy[i])
if flowerbed_copy[i] == 1:
continue
else:
if flowerbed_copy[i-1]==0 and flowerbed_copy[i+1]==0:
n -= 1
flowerbed_copy[i] = 1 #种花之后不要忘记把i位置标记为1
if n<=0:
return True
return False