zoukankan      html  css  js  c++  java
  • [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 题目总结

  • 相关阅读:
    牛客(47)求1+2+3+...+n
    牛客(48)不用加减乘除做加法
    【推荐】可编程的热键 AutoHotkey
    【Web】js 简单动画,犯了低级错误
    【分享】JDK8u241 win x64度盘下载
    【Web】开始学Web开发!
    【数组】深析 “数组名称”
    【基础向】浅析 "多(二)维数组" 的三种引用方法
    【一个小错误】通过数组指针引用数组成员
    【网络通信教程】windows 下的 socket API 编程(TCP协议)
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13900071.html
Copyright © 2011-2022 走看看