Java Straightforward Solution


  • 0
    L

    The idea is to use a boolean array pot[] to record each flower's blooming ordering. Each day a flower bloom, we check from the giving pot position forward and backward k+1 pots whether all the pots are not blooming.

    public int kEmptySlots(int[] flowers, int k) {
        if (flowers==null || flowers.length==0) return 0;
        boolean[] pot = new boolean[flowers.length];
    
        for (int i=0; i<flowers.length; i++) {
            int pos = flowers[i]-1;
            pot[pos] = true;
    
            if (pos+k+1 < pot.length && pot[pos+k+1]) {
                int j = pos+1;
                while (!pot[j] && j < pos+k+1) j++;
                if (j==pos+k+1) return i+1;
            } 
    
            if (pos-k-1 >= 0 && pot[pos-k-1]) {
                int j = pos-1;
                while (!pot[j] && j > pos-k-1) j--;
                if (j==pos-k-1) return i+1;
            }
        }
        return -1;
    }
    

  • 0
    Q

    @ll10524 what's the space and time complexity?


Log in to reply
 

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