C# O(n) solution, beats 100%


  • 0
    Y

    Basic ideas:

    Go through the array,

    1. if the value is 1, skip next one, continue to check the i+1
    2. if the value is 0, go ahead check the previous and after, if they are not 1
      2.1 plant flower
      2.2 and check, if there is no more flower need to plant, return true.
    3. return false at the end method, that means there still has flower remained to be planted.
    public bool CanPlaceFlowers(int[] flowerbed, int n)
            {
                 if (n == 0) return true;
                int i = 0;
                int len = flowerbed.Length;
                while (i < len)
                {
                    if (flowerbed[i] == 1)
                    {
                        i += 2;
                        continue;
                    }
    
                    if ((i - 1 < 0 || flowerbed[i - 1] == 0) && (i + 1 >= len || flowerbed[i + 1] == 0))
                    {
                        flowerbed[i] = 1;
                        if (--n == 0) return true;
                    }
                    i++;
                }
    
                return false;
            }
    

Log in to reply
 

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