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

栏目: 编程工具 · 发布时间: 7年前

假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给定一个花坛(表示为一个数组包含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;
    }
}复制代码

以上所述就是小编给大家介绍的《LeetCode每日一题: 种花问题(No.605)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Iterative Methods for Sparse Linear Systems, Second Edition

Iterative Methods for Sparse Linear Systems, Second Edition

Yousef Saad / Society for Industrial and Applied Mathematics / 2003-04-30 / USD 102.00

Tremendous progress has been made in the scientific and engineering disciplines regarding the use of iterative methods for linear systems. The size and complexity of linear and nonlinear systems arisi......一起来看看 《Iterative Methods for Sparse Linear Systems, Second Edition》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具