题目描述

解法

  • 贪心
    • 能种就种
    • 这里可以种花的条件是:
      • 自己为空
      • 左边为空 或者 自己是最左
      • 右边为空 或者 自己是最右
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
for (int i = 0; i < flowerbed.length; i++) {
if(flowerbed[i]==0&&(i==0||flowerbed[i-1]==0)&&(i==flowerbed.length-1||flowerbed[i+1]==0)){
//&&与||运算符具有短路效果,所以不会产生数组越界
n--;
if(n<=0){
break;
}
flowerbed[i]=1;
}
}
return n<=0;
}
}
  • 时间复杂度:O(n)

来源:力扣(LeetCode)
链接:605. 种花问题 - 力扣(LeetCode) (leetcode-cn.com)