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;
    }
}
相关推荐
重庆小透明30 分钟前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
desssq1 小时前
力扣:70. 爬楼梯
算法·leetcode·职场和发展
岁忧2 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
??tobenewyorker5 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
让我们一起加油好吗5 小时前
【基础算法】贪心 (二) :推公式
数据结构·数学·算法·贪心算法·洛谷
凌肖战8 小时前
力扣网C语言编程题:快慢指针来解决 “寻找重复数”
c语言·算法·leetcode
Alfred king20 小时前
面试150 生命游戏
leetcode·游戏·面试·数组
薰衣草23331 天前
一天两道力扣(1)
算法·leetcode·职场和发展
爱coding的橙子1 天前
每日算法刷题Day41 6.28:leetcode前缀和2道题,用时1h20min(要加快)
算法·leetcode·职场和发展
前端拿破轮1 天前
不是吧不是吧,leetcode第一题我就做不出来?😭😭😭
后端·算法·leetcode