LeetCode每日一题: 种花问题(No.605)

1,240 阅读1分钟

题目:种花问题


假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。

示例:


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

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

思考:


遍历数组,判断第count个元素前一个和后一个元素都为空才能种花,还要考虑到第一个和最后个。
满足种花条件的将数组对应位置赋值为1即种上花,然后将n--需要种的花减掉1,count++跳过当前位置下一个,因为已经种过花了。
最后判断n是否等于0即花是否全种完。

实现:


class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int length = flowerbed.length;
        for (int count = 0; count < length && n > 0; count++) {
            if (flowerbed[count] == 0 && (count == 0 || flowerbed[count - 1] == 0) && (count == length - 1|| flowerbed[count + 1] == 0)) {
                flowerbed[count] = 1;
                n--;
                count++;
            }
        }
        return n == 0;
    }
}