Description
You have a long flowerbed in which some of the 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 true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.
Examples
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
Constraints
flowerbed[i]is0or1.- There are no two adjacent flowers in
flowerbed. 0 <= n <= flowerbed.length
Code
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
for(int i = 0; i < flowerbed.size(); i++){
bool left = i == 0 || flowerbed[i - 1] == 0;
bool right = i == flowerbed.size() - 1 || flowerbed[i + 1] == 0;
if (left && right && flowerbed[i] == 0) {
flowerbed[i] = 1;
n--;
}
}
return n <= 0;
}
};Approach
NOTE
The description only specified the adjacent pots does not have flowers, so when considering the indexes
0andsize() - 1, the outer edges should automatically considered free (no flower)
- Create a for-loop that goes through the entire array
- Consider if the current index’s
leftandrightside are freeleftis free when:- Current index is at the left most side of the array
- The left adjacent index does not have a flower (0)
rightis free when:- Current index is at the right most side of the array
- The right adjacent index does not have a flower (0)
- Check if the
left,right, andcurrentindex are all 0- Since already checked
leftandrightusing Boolean, just use them in the conditional - Replace the
currentwith (1) indicating a flower can be there - Reduce the number of flowers still need to plant
- Since already checked
- Return if the number of flowers left to plant is less than or equal to 0