Maximize Distance to Closest Person

In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.

There is at least one empty seat, and at least one person sitting.

Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.

Return that maximum distance to closest person.

class Solution {
    public int maxDistToClosest(int[] seats) {
        int i=0;
        int j=0;
        int res=0;
        for(;j<seats.length;j++){
            if(seats[j]==1){
                if(i==0){
                    res=j;
                }else{
                    res=Math.max(res,(j-i+1)/2);
                }
                i=j+1;
            }
        }
        res=Math.max(res,seats.length-i);
        return res;
    }
}

This question is solved in a selected row of seats seats, seeking a position closest to the maximum distance value, i points to the first continuous current position 0, j points to the current value if i points 0, 1 and the current position, then the distance is j, otherwise, is the intermediate position i and j, res = (j-i + 1) / 2, an intermediate position, as far RES maximum value, the i point to the next position j, such as processing and finally at the rightmost position, if the last position is 0, the cycle is completed because the array is ended for traversing and will not perform if (seats [j] == 1), for the time from seats.length-i, if the last 1 elements, then it must be performed if (seats [j] == 1), at this time, I is updated to j + 1; then seats.length-i is 0, the resulting res is the last res.

Guess you like

Origin blog.csdn.net/qq_30035749/article/details/90072830