Can Place Flowers

题目
Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.

答案

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        // Start from left, try to place flower whenevr possible
        int count = 0;
        
        for(int i = 0; i < flowerbed.length; i++) {
            boolean left_clear = i - 1 < 0 || flowerbed[i - 1] != 1;
            boolean right_clear = i + 1 >= flowerbed.length || flowerbed[i + 1] != 1;
            
            if(flowerbed[i] == 0 && left_clear && right_clear) {
                flowerbed[i] = 1;
                count++;
                if(count >= n) break;
            }        
        }
        return count >= n;
    }
}

你可能感兴趣的:(Can Place Flowers)