Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
给出一个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

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理