Posted on 2023-03-20 15:38
Uriel 閱讀(40)
評論(0) 編輯 收藏 引用 所屬分類:
貪心 、
閑來無事重切Leet Code 、
大水題
給出一個0,1組成的list,要求1不能相鄰放置,問是否可以再向其中插入n個1,簡單貪心,從左邊每個0開始,符合要求就放1,看最后能不能放置>=n個
1 #605
2 #Runtime: 119 ms (Beats 83.80%)
3 #Memory: 14.3 MB (Beats 19.44%)
4
5 class Solution(object):
6 def canPlaceFlowers(self, flowerbed, n):
7 """
8 :type flowerbed: List[int]
9 :type n: int
10 :rtype: bool
11 """
12 x = 0
13 for i in range(len(flowerbed)):
14 if flowerbed[i] == 0:
15 if i >= 1:
16 if flowerbed[i - 1] == 1:
17 continue
18 if i < len(flowerbed) - 1:
19 if flowerbed[i + 1] == 1:
20 continue
21 flowerbed[i] = 1
22 x += 1
23 return x >= n