C++ O(N) without boundaries check


  • 0
    H

    Given i consecutive empty plots (0) between 2 flowers, we can easily know the maximum number of flowers we can plant is (i-1)/2, for example:

    1001 => (2-1)/2 = 0
    10001 => (3-1)/2 = 1
    100001 => (4-1)/2 = 1
    1000001 => (5-1)/2 = 2
    ...
    

    To avoid the boundary checks, we can assume there are 1 flower and 1 empty plot at begin and end of the flowerbed, i.e. 10[flowerbed]01. For begin, we can initialized cur to 1. For end, just append 01. The algorithm is to scan the flowerbed and calculate number of flowers to plant when encounter a flower.

    class Solution {
    public:
        bool canPlaceFlowers(vector<int>& flowerbed, int n) {
            int count = 0;
            int cur = 1;
            flowerbed.push_back(0);
            flowerbed.push_back(1);
            for (auto x : flowerbed) {
                if (x == 1) {
                    count += (cur-1)/2;
                    cur = 0;
                } else {
                    cur++;
                }
            }
            return count >= n;
        }
    };
    

Log in to reply
 

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