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

flowerbedi 为 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 小时前
每日算法day3—回文链表,链表分割
c语言·数据结构·算法·leetcode
zander2582 小时前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
yyds_yyd_100863 小时前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
lueluelue4712 小时前
LeetCode:链表
算法·leetcode·链表
橘子汽水16815 小时前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
Re.不晚18 小时前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展
青山木19 小时前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
星轨初途1 天前
LeetCode 热题 100——day2 字母异位词分组
c++·算法·leetcode
啦啦啦啦啦zzzz1 天前
贪心算法和动态规划
c++·算法·贪心算法·动态规划
雪碧聊技术1 天前
力扣 72. 编辑距离——动态规划经典例题
算法·leetcode·动态规划