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;
    }
}
相关推荐
圣保罗的大教堂3 小时前
leetcode 1406. 石子游戏 III 困难
leetcode
带多刺的玫瑰11 小时前
Leecode#15刷题之三数之和
算法·leetcode·职场和发展
圣保罗的大教堂11 小时前
leetcode 877. 石子游戏 中等
leetcode
shehuiyuelaiyuehao12 小时前
算法32,连续数组,前缀和+哈希表
算法·leetcode·职场和发展
Navigator_Z15 小时前
LeetCode //C - 1223. Dice Roll Simulation
c语言·算法·leetcode
Tisfy15 小时前
LeetCode 2058.找出临界点之间的最小和最大距离:遍历+遇到极值则更新(这种题谁空间复杂度不是O(1)啊)
linux·数据库·leetcode·链表·题解·模拟·遍历
小欣加油16 小时前
Leetcode2058 找出临界点之间的最小和最大距离
数据结构·c++·算法·leetcode·职场和发展
CoderYanger16 小时前
A.每日一题:3345. 最小可整除数位乘积 I
java·数据结构·程序人生·算法·leetcode·面试·学习方法
玖玥拾17 小时前
LeetCode 1 两数之和
算法·leetcode·职场和发展
旖旎夜光17 小时前
LeetCode 974:和可被 K 整除的子数组(前缀和) —— 题解
数据结构·c++·算法·leetcode·前缀和