1. 程式人生 > >【LeetCode】849. Maximize Distance to Closest Person 解題報告(Python)

【LeetCode】849. Maximize Distance to Closest Person 解題報告(Python)

目錄

題目描述

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. 1 <= seats.length <= 20000
  2. seats contains only 0s or 1s, at least one 0, and at least one 1.

題目大意

給出了一個列表表示一排座位,1代表這個位置有人坐,0代表這個位置沒人做。現在需要找一個位置坐,並找出坐在哪個位置時,離旁邊人的座位的距離最大,是多少。

解題方法

這道題是不是很眼熟呢?我翻了一下筆記,果然前幾天做過啊!現在腦子裡還有點印象:需要左右遍歷兩次。這個題目是【LeetCode】821. Shortest Distance to a Character。當時這個題目的要求是:給定字串S和屬於該字串的一個字元C,要求出字串中的每個字元到最近的C的距離。

不要看到一個是求最距離一個是求最遠距離就覺得這兩個題有不同。其實本題就是求最近距離的最大值!

上面的字串題是求每個位置到C的最近距離,其實就是這個題的每個位置到1的最近距離。上面的題是要返回一個列表,這個題是要返回列表的最大值。所以就這。

我把字串的題的解法改一下:

兩步走的方案:

第一步,先假設在很遠的位置有個座位有人坐,那麼從左到右開始遍歷,找出每個座位到其最近的左邊的有人坐的位置的距離;
第二步,再假設在很遠的位置有個座位有人坐,那麼從右到左開始遍歷,找出每個字元到其最近的右邊的有人坐的位置的距離,並和第一步求出的距離進行比較,找出最小值為結果;

最後,找出這個列表的最大值。

兩個技巧:

  1. 設了一個比字串長度更遠的一個字元C,保證後面求最小值更新距離時一定會被更新。
  2. 無論如何都用到了abs求絕對值,哪怕可能是不需要的,目的是不用費腦子思考誰大誰小了。

程式碼如下:

class Solution(object):
    def maxDistToClosest(self, seats):
        """
        :type seats: List[int]
        :rtype: int
        """
        index = -200000
        _len = len(seats)
        ans = [0] * _len
        for i in range(_len):
            if seats[i] == 1:
                index = i
            else:
                ans[i] = abs(i - index)
        index = -200000
        for i in range(_len - 1, -1, -1):
            if seats[i] == 1:
                index = i
            else:
                ans[i] = min(abs(i - index), ans[i])
        return max(ans)

日期

2018 年 6 月 10 日 —— 等了兩天的騰訊比賽複賽B的資料集,結果人家在複賽剛開始就給了。。
2018 年 11 月 22 日 —— 感恩節快樂~