Leetcode 605. Can Place Flowers
You have a long flowerbed in which some plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed
containing 0’s and 1’s, where 0
means empty and 1
means not empty, and an integer n
, return if n
new flowers can be planted in the flowerbed
without violating the no-adjacent-flowers rule.
flowerbed = [1,0,0,0,1], n = 1
true
flowerbed = [1,0,0,0,1], n = 2
false
n
is 0?
true
since we don’t need to plant any flowers.flowerbed
array will only contain 0’s and 1’s.n
.n
reaches 0, return true
.n
is still greater than 0, return false
.public class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int length = flowerbed.length;
for (int i = 0; i < length && n > 0; i++) {
if (flowerbed[i] == 0) {
boolean emptyLeft = (i == 0) || (flowerbed[i - 1] == 0);
boolean emptyRight = (i == length - 1) || (flowerbed[i + 1] == 0);
if (emptyLeft && emptyRight) {
flowerbed[i] = 1;
n--;
}
}
}
return n <= 0;
}
}
O(N)
, where N
is the number of elements in the flowerbed array. This is because we iterate through the flowerbed array once.O(1)
, as we are not using any extra space that grows with the input size.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?