[LeetCode] 849. Maximize Distance to Closest Person

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

Constraints:

  • 2 <= seats.length <= 2 * 104
  • seats[i] is 0 or 1.
  • At least one seat is empty.
  • At least one seat is occupied.

到最近的人的最大距离。

给你一个数组 seats 表示一排座位,其中 seats[i] = 1 代表有人坐在第 i 个座位上,seats[i] = 0 代表座位 i 上是空的(下标从 0 开始)。

至少有一个空座位,且至少有一人已经坐在座位上。

亚历克斯希望坐在一个能够使他与离他最近的人之间的距离达到最大化的座位上。

返回他到离他最近的人的最大距离。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximize-distance-to-closest-person
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是双指针。我们设一个变量 last = -1 表示之前遇到的一个有人的座位的下标,然后开始遍历 input 数组。当遇到一个有人坐的位置的时候,判断当前位置 i 和上一个有人坐的座位 last 的距离,这个距离的一半就是 Alex 可能可以坐下的位置。这是常规情况。注意题目最后的限制,至少有一个位置有人坐,但是也有可能只有一个位置有人坐。那么这时候在扫描 input 数组的过程中是无法得到 res 的,扫描完整个数组之后还需要再对只有一个座位有人坐的 case 进行计算(12行)。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int maxDistToClosest(int[] seats) {
 3         int last = -1;
 4         int len = seats.length;
 5         int res = 0;
 6         for (int i = 0; i < len; i++) {
 7             if (seats[i] == 1) {
 8                 res = last < 0 ? i : Math.max(res, (i - last) / 2);
 9                 last = i;
10             }
11         }
12         res = Math.max(res, len - last - 1);
13         return res;
14     }
15 }

 

LeetCode 题目总结

posted @ 2020-10-30 00:53  CNoodle  阅读(158)  评论(0编辑  收藏  举报