【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 每日一题更新

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/112058437