本文共 1277 字,大约阅读时间需要 4 分钟。
为了解决这个问题,我们需要确定在给定的数组中,最多可以种多少朵花。数组中的每个位置可以种花的条件是,相邻的位置不能有花。我们将通过遍历数组,检查每个位置是否可以种花来实现这一点。
public class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { if (n == 0) { return true; } int count = 0; int length = flowerbed.length; if (length == 0) { return false; } if (length == 1) { return flowerbed[0] == 0; } for (int i = 0; i < length; i++) { if (flowerbed[i] == 0) { boolean leftOk = (i == 0) || (flowerbed[i - 1] == 0); boolean rightOk = (i == length - 1) || (flowerbed[i + 1] == 0); if (leftOk && rightOk) { count++; flowerbed[i] = 1; } } } return count >= n; }} 这种方法确保了我们能够在O(n)时间复杂度内解决问题,适用于较大的数组。
转载地址:http://foyiz.baihongyu.com/