码迷,mamicode.com
首页 > 编程语言 > 详细

【数组】605. 种花问题

时间:2020-05-04 19:03:09      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:并且   solution   ima   img   计数器   can   pre   turn   http   

题目:

技术图片

 

 

解答:

我们从左到右扫描数组 flowerbed,如果数组中有一个 0,并且这个 0 的左右两侧都是 0,那么我们就可以在这个位置种花,即将这个位置的 0 修改成 1,并将计数器 count 增加 1。对于数组的第一个和最后一个位置,我们只需要考虑一侧是否为 0。

在扫描结束之后,我们将 count 与 n 进行比较。如果 count >= n,那么返回 True,否则返回 False。

 1 class Solution {
 2 public:
 3     bool canPlaceFlowers(vector<int>& flowerbed, int n) 
 4     {
 5         int i = 0, count = 0;
 6         while (i < flowerbed.size()) 
 7         {
 8             if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) 
 9             {
10                 flowerbed[i] = 1;
11                 count++;
12             }
13             i++;
14         }
15         return count >= n;
16 
17     }
18 };

 

【数组】605. 种花问题

标签:并且   solution   ima   img   计数器   can   pre   turn   http   

原文地址:https://www.cnblogs.com/ocpc/p/12827473.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!