zoukankan      html  css  js  c++  java
  • 849. Maximize Distance to Closest Person

    问题:

    给定0,1组成的数组,0代表空位,1代表有人坐,求使得坐在,跟最近坐的人距离最远,这个距离是多少。

    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 <= seats.length <= 20000
    seats contains only 0s or 1s, at least one 0, and at least one 1.
    

      

    解法:

    cout0计算连续的空位数。

    last1指代上一个人坐的index。

    rescout0代表最长空位长度。  rescout0=max(rescout0, cout0);

    ⚠️注意:这里区分两头和中间

    两头的cout0=实际的0位数,

    中间的cout0=(实际的0位数+1)/2

    代码参考:

     1 class Solution {
     2 public:
     3     int maxDistToClosest(vector<int>& seats) {
     4         int rescout0=0;
     5         int cout0=0, last1=-1;
     6         for(int i=0; i<seats.size(); i++){
     7             if(seats[i]==1){
     8                 if(last1==-1){
     9                     rescout0=cout0;//开头一直为0
    10                 }else{
    11                     rescout0=max(rescout0, (cout0+1)/2);
    12                 }
    13                 last1=i;
    14                 cout0=0;
    15             }else{
    16                 cout0++;
    17             }
    18         }
    19         rescout0=max(rescout0, cout0);//结尾一直为0
    20         return rescout0;
    21     }
    22 };
  • 相关阅读:
    5.3二叉树的运算
    hadoop namenode切换
    org.apache.hadoop.security.AccessControlException
    Hive中的日志
    命令大全详解
    python深浅copy
    awk命令
    head&tail命令
    cut命令
    理解inode
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12901086.html
Copyright © 2011-2022 走看看