Link
to the original question A greedy-thinking question
Idea:
- Every time you encounter a place where flowers can be planted, n is reduced by one;
- When n <= 0 is satisfied, the problem is true, and return;
- When you encounter a place that already has flowers, continue to traverse the next place;
- When you encounter a place with no flowers, see if there are flowers in the front and flowers in the back, and plant flowers if the conditions are met, that is, n minus one;
- After traversing the last element, return a boolean value of n <= 0.
The time complexity is O(n), and the space complexity is O(1).
Code:
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
for(int i = 0; i < flowerbed.size(); i++) {
if(n <= 0) {
return true;
}
if(flowerbed[i] == 1) {
continue;
}
if(i > 0 && flowerbed[i - 1] == 1) {
continue;
}
if(i < flowerbed.size() - 1 && flowerbed[i + 1] == 1) {
continue;
}
flowerbed[i] = 1;
n--;
}
return n <= 0;
}
};