力扣605. 種花問題
阿新 • • 發佈:2021-01-13
技術標籤:leetcode
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int index = 0;
while (index < flowerbed.length) {
if (flowerbed[index] == 0) {
if (index == flowerbed.length - 1 || flowerbed[index + 1] == 0) {
// 可種,種一朵,跳到下一個有可能可以種的地方,步進2
n--;
index += 2;
} else {
// 不可種,當前位置下一個位置為1,則下一個有可能可以種的地方需要步進3
index += 3;
}
} else {
// 不可種,當前位置為1,則下一個有可能可以種的地方需要步進2
index += 2;
}
}
return n <= 0;
}
}