题目
我的代码
class Solution(object):
def canPlaceFlowers(self, v, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
if len(v)==1:
if n==0:
return True
elif n==1:
return False if v[0] else True
else:
return False
i=0
limit=len(v)
count=0
if v[0]==0:
if v[1]==0:
v[0]=1
count+=1
else:
i+=3
else:
i+=2
if v[-1]==0:
if v[-2]==0:
v[-1]=1
count+=1
else:
limit-=3
else:
i-=2
print(count)
while i<limit-1:
if v[i]==0:
if v[i+1]==0:
v[i]=1
count+=1
else:
i+=3
else:
i+=2
print(v,count)
return True if count>=n else False
优秀代码(与我思路相同)
class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
m=len(flowerbed)
if m==1:
if flowerbed[0]==0 and n<=1:
return True
elif flowerbed[0]==1 and n==0:
return True
else:
return False
else:
s=0
i=0
while i<m:
if flowerbed[i]==1:
i=i+2
else:
if i==0:
if flowerbed[i+1]==0:
flowerbed[i]=1
s=s+1
i=i+1
else:
i=i+2
elif i==m-1:
if flowerbed[i-1]==0:
flowerbed[i]=1
s=s+1
i=i+2
break
else:
i=i+2
break
else:
if flowerbed[i-1]==0 and flowerbed[i+1]==0:
flowerbed[i]=1
s=s+1
i=i+2
else:
i=i+1
if s>=n:
return True
else:
return False