849. Maximize Distance to Closest Person*

849. Maximize Distance to Closest Person*

https://leetcode.com/problems/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.

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.

C++ 实现 1

要找到最大的距离, 实际是要比较三个距离, 起始距离, 中间距离以及末尾距离, 这几个距离定义如下:

  • 起始距离: [0, 0, 0, 1], 到 seats 中第一个 1 的距离, 大小为 3.
  • 中间距离: [0, 1, 0, 0, 1, 0], seats 中中间两个 1 之间的距离, 大小为 3.
  • 末尾距离: [1, 0, 0, 0], seats 从后向前, 遇到第一个 1 的距离, 大小为 3.

分别用 start_dis, mid_dis 以及 end_dis 来统计, 最后比较 start_dismid_dis / 2 以及 end_dis 的大小, 取其中的最大值即可.

使用 has_start_dis 判断是否遇到了第一个 1, 由此来更新起始距离 start_dis.
使用 j 来更新最后一个 1 的距离, 一方面可以不断更新中间距离 mid_dis, 另一方面最后可以求得末尾距离 end_dis.

class Solution {
public:
    int maxDistToClosest(vector<int>& seats) {
        int start_dis = 0, mid_dis = 0, end_dis = 0;
        bool has_start_dis = false;
        int j = -1;
        for (int i = 0; i < seats.size(); ++ i) {
            if (seats[i] == 1) { 
                if (!has_start_dis) { // 判断是否初次遇到 1
                    has_start_dis = true;
                } else {
                    mid_dis = std::max(mid_dis, i - j);
                }
                j = i;
            }
            if (!has_start_dis && seats[i] == 0) start_dis ++;
        }
        end_dis = seats.size() - 1 - j;
        if (start_dis >= mid_dis / 2 && start_dis >= end_dis)
            return start_dis;
        else if (end_dis > mid_dis / 2 && end_dis > start_dis)
            return end_dis;
        else
            return mid_dis / 2;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值