zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    C#中的运算符和表达式
    C#的常量和变量以及其作用域和命名规范
    C#中(int)、int.Parse()、int.TryParse()和Convert.ToInt32()的区别
    在咸阳机场等候登机有感
    关于博客的回忆
    String、StringBuffer、StringBuilder有什么区别
    谈谈你对Java异常处理机制的理解
    谈谈你对 Java 平台的理解?
    所谓的产品经理
    mysql数据库开发常见问题及优化
  • 原文地址:https://www.cnblogs.com/ordili/p/9992225.html
Copyright © 2011-2022 走看看