C++ solution


  • 0
    B

    the solution contains two passes

    the first pass finds all 1, and change the element before and after each 1 to 1

    in the second pass, every 0 is a possible flower position, so if we meet a 0 we plant a flower and skip one slot

    class Solution {
    public:
        bool canPlaceFlowers(vector<int>& flowerbed, int n) {
            int len = flowerbed.size();
            for(int i = 0; i < len; i++ )
            {
                if(flowerbed[i] == 0) continue;
                if(i > 0) flowerbed[i-1] = 1;
                if(i + 1 < len) flowerbed[++i] = 1;
            }
    
            for(int i = 0; i < len && n > 0; i++ )
            {
                if(flowerbed[i] == 1) continue;
                flowerbed[i++] = 1;
                n--;
            }
            
            return n == 0;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.