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;
    }
}

这道题求解的是在一排座位中选座,求离最近位置最大的距离值,i指向当前连续为0的第一个位置,j指向当前值,如果i指向0,且当前位置为1,那么距离就是j,否则,就是i和j的中间位置,res=(j-i+1)/2,中间位置,res为目前为止最大值,将i指向j的下一个位置,如最后再处理一下最右边的位置,如果最后一个位置是0,则for循环因为数组遍历完成而结束且不会执行if(seats[j]==1),此时距离为seats.length-i,如果最后的元素为1,那么它一定会执行if(seats[j]==1),此时,i会更新为j+1;那么seats.length-i就是0,所得的res就是上一次的res。

猜你喜欢

转载自blog.csdn.net/qq_30035749/article/details/90072830