LeetCode 605. 种花问题

27 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第20天,点击查看活动详情

一、题目描述:

605. 种花问题 - 力扣(LeetCode)

假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

给你一个整数数组  flowerbed 表示花坛,由若干 01 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false

 

示例 1:

输入:flowerbed = [1,0,0,0,1], n = 1
输出:true

示例 2:

输入:flowerbed = [1,0,0,0,1], n = 2
输出:false

 

提示:

  • 1 <= flowerbed.length <= 2 * 10^4
  • flowerbed[i] 为 0 或 1
  • flowerbed 中不存在相邻的两朵花
  • 0 <= n <= flowerbed.length

二、思路分析:

  1. 为了避免对目标数组判断时造成越界,在目标数组头部尾部分别增加一个元素0
  2. 遍历目标数组(不包括边界处的两个0),判断当前位置是否种了花,如果种了花,直接判断下一个位置,如果没有种花,则继续判断它的相邻位置是否种植了花,都没有种,说明该位置可以种植花,表示花坛还可以种植多少花的变量加1,其他情况不可以种植
  3. 对花坛还可以种植的花数和想要种的花数进行比较,前者大于等于后者,返回为真,否则返回为假

三、AC 代码:

class Solution {
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
         int m=flowerbed.size();
         int tree=0;
         flowerbed.push_back(0);
         flowerbed.insert(flowerbed.begin(),0);
         for(int i=1;i<m+1;i++)
         {
            if(flowerbed[i]==0)
            {
                if(flowerbed[i-1]==0&&flowerbed[i+1]==0) 
                {
                    flowerbed[i]=1;
                    tree++;
                }
            }
         }
         if(n<=tree) return true;
         else return false;
    }
};

范文参考:

在收尾个加上一个0,然后直接判断连续三个的0,且n的值也应该大于0,也需要注意变换插入花朵地方的值,将其变为1. - 种花问题 - 力扣(LeetCode)