LeetCode 605. Flowering problem

Link
to the original question A greedy-thinking question
Idea:

  1. Every time you encounter a place where flowers can be planted, n is reduced by one;
  2. When n <= 0 is satisfied, the problem is true, and return;
  3. When you encounter a place that already has flowers, continue to traverse the next place;
  4. 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;
  5. 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;
    }
};

Guess you like

Origin blog.csdn.net/qq_43078427/article/details/112365138