【贪心】B_013 种花问题(错误枚举 | 防御式编程 | 模拟)

一、题目描述

Suppose 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 - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.

Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: False
Note:
The input array won't violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won't exceed the input array size.

二、题解

方法一:错误枚举

遇到 1 就枚举前两个位置是否为 0,但是没有当前位置是 0,后序位置没有 1 的情况。 即这种情况:

[0,0,1,0,1]
1
public boolean canPlaceFlowers(int[] f, int n) {
    int count = 0, N = f.length;

    for (int i = 0; i < N; i++) {
        if (f[i] == 1)
            continue;
        for (int j = i + 2; j < N; j += 2) {
            if (f[j] == 0 && f[j - 1] == 0 && f[j + 1] == 0) {
                count++;
                f[j] = 1;
                break;
            }
        }
    }
    return count >= n;
}

防御式编程: 一种比较直观的做法就是在数组 f 的首尾各加 1 个前导 0,这样就不必考虑边界。


复杂度分析

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(n)O(n)

方法二:贪心

  • 遇到 0 就判断它的前后是否为 0。
    • 如果 f[i-1]f[i+1] 都为 0 则可种。
    • 否则,跳过。
  • 边界问题:
    • i = 0,则默认 last 为 0.
    • i = N-1,则默认 next = 0
public boolean canPlaceFlowers(int[] f, int n) {
    int count = 0, N = f.length;
    for (int i = 0; i < N; i++) {
        if (f[i] == 1)
            continue;
        int last = i == 0 ? 0 : f[i-1];
        int next = i == N-1 ? 0 : f[i+1];
        if (last == 0 && next == 0) {
            count++;
            f[i] = 1;
        } 
    }
    return count >= n;
}

复杂度分析

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章