LeetCode_贪心算法_简单_605.种花问题

目录

1.题目

假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。给你一个整数数组 flowerbed 表示花坛,由若干 0 和 1 组成,其中 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 * 104

flowerbed[i] 为 0 或 1

flowerbed 中不存在相邻的两朵花

0 <= n <= flowerbed.length

2.思路

(1)贪心算法

3.代码实现(Java)

java 复制代码
//思路1------------贪心算法
class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int length = flowerbed.length;
        //上一个花所在的下标
        int prev = -1;
        int res = 0;
        for (int i = 0; i < length; i++) {
            if (flowerbed[i] == 1) {
                if (prev < 0) {
                    res += i / 2;
                } else {
                    res += (i - prev - 2) / 2;
                }
                prev = i;
            }
        }
        if (prev < 0) {
	        //数组 flowerbed 的值全为 0
            res += (length + 1) / 2;
        } else {
            res += (length - prev - 1) / 2;
        }
        return res >= n;
    }
}
相关推荐
叶小鸡1 小时前
小鸡玩算法-力扣HOT100-动态规划(下)
算法·leetcode·动态规划
毅炼4 小时前
今日LeetCode 摸鱼打卡
java·算法·leetcode
m0_629494734 小时前
LeetCode 热题 100-----28. 两数相加
数据结构·算法·leetcode·链表
菜菜的顾清寒4 小时前
力扣HOT100(25)环形链表
算法·leetcode·链表
Controller-Inversion8 小时前
76. 最小覆盖子串
java·算法·leetcode
_日拱一卒8 小时前
LeetCode:437路径总和Ⅲ
算法·leetcode·职场和发展
世纪末的小黑8 小时前
【LeetCode自用】LeetCode自用记录贴,题目一:两数之和
数据结构·算法·leetcode
兰令水8 小时前
topcode【随机算法题】【2026.5.22打卡-java版本】
java·算法·leetcode
水木流年追梦21 小时前
大模型入门-Reward 奖励模型训练
开发语言·python·算法·leetcode·正则表达式
始三角龙1 天前
LeetCode hoot 100 -- 缺失的第一个正整数
算法·leetcode·职场和发展