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;
    }
}
相关推荐
琢磨先生David4 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll4 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐4 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶4 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER4 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了4 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333334 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录4 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1234 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode