leetcode 849. Maximize Distance to Closest Person

博客围绕座位安排问题展开,给定座位数组,1表示有人,0表示空位,要找出空位离最近有人座位的最大距离。介绍了具体思路,通过循环处理,针对不同情况(两边有1、单边到边界)计算距离并更新最大距离。

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.

    Example 1:
    
    Input: [1,0,0,0,1,0,1]
    Output: 2
    Explanation: 
    If Alex sits in the second open seat (seats[2]), then the closest person has distance 2.
    If Alex sits in any other open seat, the closest person has distance 1.
    Thus, the maximum distance to the closest person is 2.
    Example 2:
    
    Input: [1,0,0,0]
    Output: 3
    Explanation: 
    If Alex sits in the last seat, the closest person is 3 seats away.
    This is the maximum distance possible, so the answer is 3.

Note:

1 <= seats.length <= 20000
seats contains only 0s or 1s, at least one 0, and at least one 1.

题目的意思就是要找到 离这个0最近的1的距离的最大值。
具体思路如下:
一个循环,如果当前值是0,就找最近的1的距离的最大值,如果是1,就跳过。
当然找0还分为几种情况:

 1. 最简单的一种:两边都有1,这时候从两边的距离中选出最短的距离,和之前的最长距离比较,如果大于之前的更换,如果小于不管。
 2. 如果往左边找或者右边找找不到1就到边界了,此时你肯定不能用到边界的距离当做到1的距离,因为这一边到边界的距离不存在,在这里我的处理方式是定义两个flag(按照题目的要求,只会只有最多一边找不到1),如果往右边找不到,那么让它到右边的距离等于左边找到1的距离,左边同理可得。

 

    int maxDistToClosest(vector<int>& seats) {
        int length = seats.size();
        int closest = 0;
        for(int i = 0 ; i < length ; i++)
        {
            if(seats[i] == 1)
                continue;
            int left_min=0,right_min=0;
            int flag_left = 0,flag_right = 0;
            //左边开始找
            for(int m = i - 1 ; m >= 0 ; m --)
            {
                left_min++;
                if(seats[m] == 1)
                {
                //左边找到了
                    flag_left = 1;
                    break;
                }   
            }
            //右边开始找
            for(int n = i+1;n<=seats.size()-1;n++)
            {
                right_min++;
                if(seats[n] == 1)
                {
                //右边找到了
                    flag_right = 1;
                    break;
                }
            }
            if (flag_left == 0)
            {
                left_min = right_min;
            }
            
            if(flag_right == 0)
            {
                right_min = left_min;
            }
            
            closest = max(closest,min(left_min,right_min));
        }
        return closest;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值