Swift solution


  • 0
    class Solution {
        func canPlaceFlowers(_ flowerbed: [Int], _ n: Int) -> Bool {
            if flowerbed.count == 0 {
                return false
            }
            
            let count = flowerbed.count
            var preZero = flowerbed[0] == 0
            var canPlant = 0
            
            for i in 0..<count {
                if flowerbed[i] == 0 {
                    if preZero && (i == count - 1 || flowerbed[i + 1] == 0) {
                        canPlant += 1
                        preZero = false
                    } else {
                        preZero = true
                    }
                } else {
                    preZero = false
                }
            }
            
            return n <= canPlant
        }
    }
    

Log in to reply
 

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