leetcode605

public class Solution {
    public bool CanPlaceFlowers(int[] flowerbed, int n) {
        if (flowerbed.Length == 1 && flowerbed[0] == 0)
            {
                n = n - 1;
                if (n <= 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }            

            var conti = 0;
            var firstOne = false;
            for (int i = 0; i < flowerbed.Length; i++)
            {
                if (flowerbed[i] == 0)
                {
                    conti++;
                }
                else
                {
                    if (firstOne)
                    {
                        if (conti <= 2)
                        {
                            conti = 0;
                        }
                        else
                        {
                            if (conti % 2 == 0)
                            {
                                n = n - (conti / 2 - 1);
                            }
                            else
                            {
                                n = n - ((conti + 1) / 2 - 1);
                            }
                            if (n <= 0)
                            {
                                return true;
                            }
                            conti = 0;
                        }
                    }
                    else
                    {
                        if (conti <= 1)
                        {
                            conti = 0;
                        }
                        else
                        {
                            n = n - (conti / 2);
                            if (n <= 0)
                            {
                                return true;
                            }
                            conti = 0;
                        }
                    }
                    firstOne = true;
                }
            }
            if (conti <= 1)
            {
                conti = 0;
            }
            else
            {
                if (firstOne)
                {
                    n = n - (conti / 2);
                }
                else
                {
                    n = n - (conti + 1) / 2;
                }
            }
            if (n <= 0)
            {
                return true;
            }
            else
            {
                return false;
            }
    }
}

https://leetcode.com/problems/can-place-flowers/#/description

原文地址:https://www.cnblogs.com/asenyang/p/6943308.html