• [LeetCode] 849. Maximize Distance to Closest Person


    You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).

    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 the closest person.

    Example 1:

    Input: seats = [1,0,0,0,1,0,1]
    Output: 2
    Explanation: 
    If Alex sits in the second open seat (i.e. 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: seats = [1,0,0,0]
    Output: 3
    Explanation: 
    If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.
    This is the maximum distance possible, so the answer is 3.
    

    Example 3:

    Input: seats = [0,1]
    Output: 1

    Constraints:

    • 2 <= seats.length <= 2 * 104
    • seats[i] is 0 or 1.
    • At least one seat is empty.
    • At least one seat is occupied.

    到最近的人的最大距离。在一排座位上,seats[i] = 1表示那个位置上有人坐,如果是0则是没有人坐。现在至少有一个空座位,也至少有一个人坐下了。Alex试图找一个位置坐下,他希望坐在一个能够使他与离他最近的人之间的距离达到最大化的座位上。返回那个理想的座位的下标。

    思路是双指针。我们设一个变量last = -1表示之前遇到的一个有人的座位的下标,然后开始遍历input数组。当遇到一个有人坐的位置的时候,判断这个位置和last的距离,这个距离的一半就是Alex可能可以坐下的位置。这是常规情况。注意题目最后的限制,至少有一个位置有人坐,但是也有可能只有一个位置有人坐。那么这时候在扫描input数组的过程中是无法得到res的,此时还需要对只有一个座位有人坐的case进行计算(12行)。

    时间O(n)

    空间O(1)

    Java实现

     1 class Solution {
     2     public int maxDistToClosest(int[] seats) {
     3         int last = -1;
     4         int len = seats.length;
     5         int res = 0;
     6         for (int i = 0; i < len; i++) {
     7             if (seats[i] == 1) {
     8                 res = last < 0 ? i : Math.max(res, (i - last) / 2);
     9                 last = i;
    10             }
    11         }
    12         res = Math.max(res, len - last - 1);
    13         return res;
    14     }
    15 }

    LeetCode 题目总结

  • 相关阅读:
    如何看linux是32位还是64位
    Linux下,命令 wget 的使用
    express框架目录结构
    怎么在centos中查看某个目录的树结构?
    CentOS minimal版安装图形界面的步骤(自动获取IP)
    微信小程序项目,实现图书搜索组件完善
    微信小程序项目,实现图书搜索高阶组件:
    微信小程序中使用音频组件以及wx:if和hidden的区别
    微信小程序绑定数据以及自定义指令
    微信小程序定义一个组件
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13900071.html
Copyright © 2020-2023  润新知