CanPlaceFlowers
Description
- 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
Solution
贪心思想
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int len = flowerbed.length;
int cnt = 0;
for (int i = 0; i < len && cnt < n; i++) {
if (flowerbed[i] == 1) {
continue;
}
//下面两行的代码很好,将遍历的前驱和后继都拿出来了
int pre = i == 0 ? 0 : flowerbed[i - 1];
int next = i == len - 1 ? 0 : flowerbed[i + 1];
if (pre == 0 && next == 0) {
cnt++;
flowerbed[i] = 1;
}
}
return cnt >= n;
}
Appendix
1.代码不是我自己写的,转自GitHub