6 ms solution in C


  • 0
    B
    bool canPlaceFlowers(int* flowerbed, int flowerbedSize, int n) {
        int i = 0, previous, current, next;
        for( ; i < flowerbedSize ; i++)
        {
            if(n == 0)
                break;
            current = *(flowerbed + i);
            if(i == 0 && flowerbedSize > 1)
            {
                next = *(flowerbed + i + 1);
                if(current == 0 && next == 0)
                {
                    *(flowerbed + i) = 1;
                    n--;
                }
            }
            else if(i == (flowerbedSize - 1) && flowerbedSize > 1)
            {
                previous = *(flowerbed + i - 1);
                if(current == 0 && previous == 0)
                {
                    *(flowerbed + i) = 1;
                    n--;
                }
            } 
            else
            {
                previous = *(flowerbed + i - 1);
                next = *(flowerbed + i + 1);
                if(previous == 0 && current == 0 && next == 0)
                {
                    *(flowerbed + i) = 1;
                    n--;
                }
            }
        }
        if(n == 0)
            return true;
        else
            return false;
    }
    

Log in to reply
 

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