当前位置:网站首页>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});//选择最大值
}
};
边栏推荐
- Vulkan performance and refinement
- 关于XML一些介绍和注意事项
- NC50965 Largest Rectangle in a Histogram
- 百数不断创新,打造自由的低代码办公工具
- 奥斯陆大学:Li Meng | 基于Swin-Transformer的深度强化学习
- Overlay of shutter (Pop-Up)
- Helm basic learning
- Two common methods and steps of character device registration
- Nc20806 District interval
- Basic use of shell script
猜你喜欢

Teach you JDBC hand in hand -- structure separation

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

百数不断创新,打造自由的低代码办公工具

Multiprocess programming (I): basic concepts

【AutoSAR 七 工具链简介】

Pageoffice - bug modification journey

Explain in detail the significance of the contour topology matrix obtained by using the contour detection function findcontours() of OpenCV, and how to draw the contour topology map with the contour t
【AutoSAR 五 方法论】

可下载《2022年中国数字化办公市场研究报告》详解1768亿元市场

Logback configuration file
随机推荐
JSON conversion tool class
【AutoSAR 八 OS】
Multi process programming (III): message queue
Free we media essential tools sharing
Liad: the consumer end of micro LED products is first targeted at TVs above 100 inches. At this stage, it is still difficult to enter a smaller size
程序分析与优化 - 9 附录 XLA的缓冲区指派
kubernetes编写yml简单入门
Hundreds of continuous innovation to create free low code office tools
腾讯云免费SSL证书扩展文件含义
2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
Tensorflow 2. Chapter 15 of X (keras) source code explanation: migration learning and fine tuning
File operation io-part2
Vulkan-性能及精细化
MySQL 23道经典面试吊打面试官
详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图
Helm basic learning
Vulkan is not a "panacea"“
Rust string slicing, structs, and enumeration classes
百数不断创新,打造自由的低代码办公工具
Hdu3507 (slope DP entry)