leetcode - 849.Maximize Distance to Closest Person - Java

You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
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 the closest person.

在这里插入图片描述

Example 1:

Input: seats = [1,0,0,0,1,0,1]
Output: 2
Explanation:
If Alex sits in the second open seat (i.e. 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: seats = [1,0,0,0]
Output: 3
Explanation:
If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.

Example 3:

Input: seats = [0,1]
Output: 1

题目解析:坐下每个点距离最近的人的距离,这要求我们要知道左右两边人的距离,也就是min(left, right),我们可以选择先计算出所有点距左右两边的人的距离,再进行判断,或者每到一个点计算左右两边距离取最小值。

  1. 提前计算所有点距左右两边的距离
public int maxDistToClosest(int[] seats) {
        int length = seats.length;
        int[] left = new int[length];
        int[] right = new int[length];
        Arrays.fill(left, length);
        Arrays.fill(right, length);
        //获取到每个可坐下的点距左边边的人的距离
        for (int i = 0; i < length; i++) {
            if (seats[i] == 1) left[i] = 0;
            else if (i > 0) left[i] = left[i - 1] + 1;
        }
        //获取到每个可坐下的点距右边的人的距离
        for (int i = length - 1; i >= 0; i--) {
            if (seats[i] == 1) right[i] = 0;
            else if (i < length - 1) right[i] = right[i + 1] + 1;
        }
        int maxDis = 0;
        //获取每个点据人的最小值中的最大值
        for (int i = 0; i < length; i++) {
            if (seats[i] == 0)
                maxDis = Math.max(maxDis, Math.min(left[i], right[i]));
        }
        return maxDis;
    }
  1. 每到一个点进行计算
public int maxDistToClosest(int[] seats) {
        int N = seats.length;
        int prev = -1, future = 0;
        int ans = 0;

        for (int i = 0; i < N; ++i) {
            if (seats[i] == 1) {
                prev = i;
            } else {
                while (future < N && seats[future] == 0 || future < i)
                    future++;

                int left = prev == -1 ? N : i - prev;
                int right = future == N ? N : future - i;
                ans = Math.max(ans, Math.min(left, right));
            }
        }

        return ans;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值