Java Solution--Simple Logic


  • 0
    R
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
            List<int[]> intervals = new ArrayList<>();
            if(flowerbed == null)   return false;
            if(n == 0)  return true;
            if(flowerbed.length == 1)    return n == 1 && flowerbed[0] == 0;
            // add zero sequence start and end index to interval list
            for(int i = 0; i < flowerbed.length; i++) {
                if(flowerbed[i] == 0) {
                    int start = i;                                                      //    s     e
                    while(i+1 < flowerbed.length && flowerbed[i+1] == 0)    i++;        //  1 0 0 0 0 1
                    intervals.add(new int[]{start, i});
                }
            }
            int available = 0;
            for(int[] plot : intervals) {
                int start = plot[0];
                int end = plot[1];
                // none 1 at two side  of zeros sequence
                if(start == 0 && end == flowerbed.length-1) {
                    available += (end-start+2)/2;
                }
                //  one 1 at two side of zeros sequence
                else if(start == 0 || end == flowerbed.length-1) {
                    available += (end-start+1)/2;
                }
                // two 1 at two side  of zeros sequence
                else available += (end-start)/2;
            }
            return available >= n;
        }
    `

Log in to reply
 

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