849. Maximize Distance to Closest Person

喜你入骨 提交于 2019-12-28 11:21:06

1. Question

849. Maximize Distance to Closest Person

url https://leetcode.com/problems/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. 

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.

2. Solution

class Solution:
    def maxDistToClosest(self, seats):
        """
        :type seats: List[int]
        :rtype: int
        """

        size = len(seats)
        right_dis_list = [0 for v in range(size)]

        # 最右边无人,距离设置最大
        if seats[-1] == 0:
            right_dis_list[-1] = size + 1
        # 最右边有人,距离设置为0
        else:
            right_dis_list[-1] = 0

        for i in range(-2, -size - 1, -1):
            # 当前位置有人,距离设置为0
            if seats[i] == 1:
                right_dis_list[i] = 0
            # 当前位置无人,距离设置为右边距离+1
            else:
                right_dis_list[i] = right_dis_list[i + 1] + 1

        # print(right_dis_list)
        if seats[0] == 1:
            left_dis = 0
        else:
            left_dis = size + 1

        max_dis = 0
        max_dis = min(left_dis, right_dis_list[0])

        for i in range(1, size):

            # 当前位置有人
            if seats[i] == 1:
                left_dis = 0
                continue

            left_dis += 1
            # 当前位置无人
            if seats[i] == 0:
                max_dis = max(max_dis, min(left_dis, right_dis_list[i]))

        return max_dis
        

3. Complexity Analysis

Time Complexity : O(N)

Space Complexity: O(N)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!