• 849. Maximize Distance to Closest Person


    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)

  • 相关阅读:
    随手记
    jira默认是jira_user用户组的用户有登录jira的权限 上海
    loadrunner11安装 上海
    虚拟机增加内存方法 上海
    centos6中安装VMware Tools 上海
    linux安装过程中遇到的一些问题总结 上海
    C语言指针方法对字符串进行去重 上海
    在linux环境下搭建JDK+JAVA+Mysql,并完成jforum的安装 上海
    关于pl/sql打开后database为空的问题解决办法 上海
    字符串表达式求值(支持多种类型运算符)
  • 原文地址:https://www.cnblogs.com/ordili/p/9992225.html
Copyright © 2020-2023  润新知