【LeetCode】605. Can Place Flowers 种花问题(Easy)(JAVA)每日一题

【LeetCode】605. Can Place Flowers 种花问题(Easy)(JAVA)

题目地址: https://leetcode.com/problems/can-place-flowers/

题目描述:

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

Given an integer array flowerbed containing 0’s and 1’s, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.

Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true

Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2
Output: false

Constraints:

  • 1 <= flowerbed.length <= 2 * 10^4
  • flowerbed[i] is 0 or 1.
  • There are no two adjacent flowers in flowerbed.
  • 0 <= n <= flowerbed.length

题目大意

假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。

解题方法

  1. 采用贪心算法,遇到 0,只要当前 i = 0 或者 flowerbed[i - 1] = 0 就把当前元素置位 1,并且 n - 1
  2. 如果 flowerbed[i] == 1,并且前面的 flowerbed[i - 1] == 1,表示前面的那次放置 1 失败了,需要加回去 n + 1
  3. 知道 n 为 0 为止
class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        if (n <= 0) return true;
        for (int i = 0;i < flowerbed.length; i++) {
            if (flowerbed[i] == 1) {
                if (i > 0 && flowerbed[i - 1] == 1) n++;
            } else {
                if (i == 0 || (i > 0 && flowerbed[i - 1] == 0)) {
                    n--;
                    flowerbed[i] = 1;
                }
            }
            if (n == 0 && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) return true;
        }
        return false;
    }
}

执行耗时:1 ms,击败了100.00% 的Java用户
内存消耗:40.2 MB,击败了21.04% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值