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 one0
, and at least one1
.
這道題給了我們一個只有0和1且長度為n的數組,代表n個座位,其中0表示空座位,1表示有人座。現在說是愛麗絲想找個位置坐下,但是希望能離最近的人越遠越好,這個不難理解,就是想左右兩邊盡量跟人保持距離,讓我們求這個距離最近的人的最大距離。來看題目中的例子1,有三個空位連在一起,那么愛麗絲肯定是坐在中間的位置比較好,這樣跟左右兩邊人的距離都是2。例子2有些特別,當空位連到了末尾的時候,這里可以想像成靠牆,那么靠牆坐肯定離最遠啦,所以例子2中愛麗絲坐在最右邊的位子上距離左邊的人距離最遠為3。那么不難發現,愛麗絲肯定需要先找出最大的連續空位長度,若連續空位靠着牆了,那么就直接挨着牆坐,若兩邊都有人,那么就坐到空位的中間位置。如何能快速知道連續空位的長度呢,只要知道了兩邊人的位置,相減就是中間連續空位的個數。所以博主最先使用的方法是用一個數組來保存所有1的位置,即有人坐的位置,然后用相鄰的兩個位置相減,就可以得到連續空位的長度。當然,靠牆這種特殊情況要另外處理一下。當把所有1位置存入數組 nums 之后,開始遍歷 nums 數組,第一個人的位置有可能不靠牆,那么他的位置坐標就是他左邊靠牆的連續空位個數,直接更新結果 res 即可,因為靠牆連續空位的個數就是離右邊人的最遠距離。然后對於其他的位置,我們減去前一個人的位置坐標,然后除以2,更新結果 res。還有最右邊靠牆的情況也要處理一下,就用 n-1 減去最后一個人的位置坐標,然后更新結果 res 即可,參見代碼如下:
解法一: ``` class Solution { public: int maxDistToClosest(vector
我們也可以只用一次遍歷,那么就需要在遍歷的過程中統計出連續空位的個數,即連續0的個數。那么采用雙指針來做,start 指向連續0的起點,初始化為0,i為當前遍歷到的位置。遍歷 seats 數組,跳過0的位置,當遇到1的時候,此時先判斷下 start 的值,若是0的話,表明當前這段連續的空位是靠着牆的,所以要用連續空位的長度 i-start 來直接更新結果 res,否則的話就是兩頭有人的中間的空位,那么用長度加1除以2來更新結果 res,此時 start 要更新為 i+1,指向下一段連續空位的起始位置。for 循環退出后,還是要處理最右邊靠牆的位置,用 n-start 來更新結果 res 即可,參見代碼如下:
解法二: ``` class Solution { public: int maxDistToClosest(vector
討論:這道題的一個很好的 follow up 是讓我們返回愛麗絲坐下的位置,那么要在結果 res 可以被更新的時候,同時還應該記錄下連續空位的起始位置 start,這樣有了 start 和 最大距離 res,那么就可以定位出愛麗絲的座位了。
Github 同步地址:
https://github.com/grandyang/leetcode/issues/849
類似題目:
參考資料:
https://leetcode.com/problems/maximize-distance-to-closest-person/