133.Maximize Distance to Closest Person

题目:

In a row of seats1 represents a person sitting in that seat, and 0 represents that the seat is empty. 

在一排座位中,1表示坐在该座位上的人,0表示座位是空的。

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.
如果亚历克斯坐在第二个开放座位(座位[2]),那么最近的人有距离2。 If Alex sits in any other open seat, the closest person has distance 1.
如果Alex坐在任何其他开放式座位上,则最近的人的距离为1。 Thus, the maximum distance to the closest person is 2.
因此,到最近的人的最大距离是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.
如果Alex坐在最后一个座位上,那么最近的人就是3个座位。 This is the maximum distance possible, so the answer is 3.
这是可能的最大距离,所以答案是3。

Note:

扫描二维码关注公众号,回复: 3036300 查看本文章
  1. 1 <= seats.length <= 20000
  2. seats contains only 0s or 1s, at least one 0, and at least one 1.席位仅包含0或1,至少一个0,至少一个1。

解答:

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

详解:

计算前缀中连续零的数量,res = max(res,zeros)
计算中间连续零的数量,res = max(res,(zeros + 1)/ 2)
计算后缀中连续零的数量,res = max(res,zeros)

猜你喜欢

转载自www.cnblogs.com/chanaichao/p/9580470.html