1. 程式人生 > 其它 >【LeetCode】605. Can Place Flowers 種花問題(Easy)(JAVA)每日一題

【LeetCode】605. Can Place Flowers 種花問題(Easy)(JAVA)每日一題

技術標籤:LeetCode 每日一題javaleetcode演算法面試資料結構

【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 arrayflowerbedcontaining 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 flowerbedwithout 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 每日一題更新