Java Solution 11ms


  • 0
    A

    public class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
    int length = flowerbed.length;
    if(length == 1 && n < 2) {
    if(flowerbed[0] == 0 && n == 1) {
    return true;
    }
    }
    int count = 0;
    for(int i = 0; i < length; i++) {
    if(flowerbed[i] == 0) {
    int nextElement = (i == length - 1) ? 0 : flowerbed[i + 1];
    int prevElement = (i == 0) ? 0 : flowerbed[i - 1];
    if(nextElement == 0 && prevElement == 0) {
    if(length % 2 == 0) {
    i+=2;
    } else {
    i++;
    }
    count++;
    }
    }
    if(count >= n) {
    return true;
    }
    }
    return false;

    }
    

    }


Log in to reply
 

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