当前位置:网站首页>leetcode-849:到最近的人的最大距离
leetcode-849:到最近的人的最大距离
2022-07-02 23:55:00 【菊头蝙蝠】
题目
给你一个数组 seats 表示一排座位,其中 seats[i] = 1 代表有人坐在第 i 个座位上,seats[i] = 0 代表座位 i 上是空的(下标从 0 开始)。
至少有一个空座位,且至少有一人已经坐在座位上。
亚历克斯希望坐在一个能够使他与离他最近的人之间的距离达到最大化的座位上。
返回他到离他最近的人的最大距离。
示例 1:
输入:seats = [1,0,0,0,1,0,1]
输出:2
解释:
如果亚历克斯坐在第二个空位(seats[2])上,他到离他最近的人的距离为 2 。
如果亚历克斯坐在其它任何一个空位上,他到离他最近的人的距离为 1 。
因此,他到离他最近的人的最大距离是 2 。
示例 2:
输入:seats = [1,0,0,0]
输出:3
解释:
如果亚历克斯坐在最后一个座位上,他离最近的人有 3 个座位远。
这是可能的最大距离,所以答案是 3 。
示例 3:
输入:seats = [0,1]
输出:1
解题
方法一:一次遍历
总共有三种情况
- 1.计算左边第一个有人的位置到左边的第一个位置距离(亚历克斯可以坐到最左边)
- 2.计算最右边有人的位置到最后一个位置距离(亚历克斯可以坐到最右边)
- 3.计算两个有人位置间的距离(亚历克斯可以坐到两个人中间)
取这三种情况的最大值就行了。
class Solution {
public:
int maxDistToClosest(vector<int>& seats) {
int n=seats.size();
int first,pre,last;//记录最左边的有人的座位、上一个有人的座位、最后一个有人的座位
int maxInterval=INT_MIN;//记录两个座位之间最大间距
int count=0;
for(int i=0;i<n;i++){
if(seats[i]==1){
if(count==0){
//如果是第一个有人的座位
first=i;
last=i;
}else if(count>=1){
//如果是第一个以后 有人的座位
pre=last;
last=i;
maxInterval=max(maxInterval,last-pre);//保存当前有人的座位和上一个有人的座位 的 最大间距
}
count++;
}
}
return max({
first,n-1-last,maxInterval/2});//选择最大值
}
};
边栏推荐
- JSON转换工具类
- UART、RS232、RS485、I2C和SPI的介绍
- Hundreds of continuous innovation to create free low code office tools
- lex && yacc && bison && flex 配置的问题
- LeedCode1480. Dynamic sum of one-dimensional array
- 机器学习:numpy版本线性回归预测波士顿房价
- NC50528 滑动窗口
- Rust ownership (very important)
- 2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
- node_modules删不掉
猜你喜欢

MySQL 23 classic interview hanging interviewer

MySQL 23道经典面试吊打面试官

University of Toronto:Anthony Coache | 深度强化学习的条件可诱导动态风险度量

【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议

Teach you JDBC hand in hand -- structure separation

Illustrated network: what is virtual router redundancy protocol VRRP?

logback配置文件

Nacos+openfeign error reporting solution

pod生命周期详解

【AutoSAR 九 C/S原理架构】
随机推荐
【AutoSAR 六 描述文件】
Overlay of shutter (Pop-Up)
FAQ | FAQ for building applications for large screen devices
The most painful programming problem in 2021, adventure of code 2021 Day24
Shell 实现文件基本操作(sed-编辑、awk-匹配)
mm中的GAN模型架构
ftrace工具的介绍及使用
Multiprocess programming (V): semaphores
【AutoSAR 三 RTE概述】
There is an unknown problem in inserting data into the database
Helm basic learning
Vulkan is not a "panacea"“
百度智能云牵头打造智能云综合标准化平台
Some introduction and precautions about XML
Hundreds of continuous innovation to create free low code office tools
How to find out the currently running version of Solr- How do I find out version of currently running Solr?
Automated defect analysis in electronic microscopic images
An excellent orm in dotnet circle -- FreeSQL
免费自媒体必备工具分享
NC17059 队列Q