当前位置:网站首页>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});//选择最大值
}
};
边栏推荐
- [jetcache] jetcache configuration description and annotation attribute description
- University of Toronto:Anthony Coache | 深度强化学习的条件可诱导动态风险度量
- NC17059 队列Q
- Is there a free text to speech tool to help recommend?
- 【雅思阅读】王希伟阅读P1(阅读判断题)
- 简单聊聊运维监控的其他用途
- Overlay of shutter (Pop-Up)
- Kubernetes simple introduction to writing YML
- 1.12 - 指令
- NC50965 Largest Rectangle in a Histogram
猜你喜欢
1.11 - bus
[IELTS reading] Wang Xiwei reading P1 (reading judgment question)
University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
Redis21 classic interview questions, extreme pull interviewer
Pageoffice - bug modification journey
UART、RS232、RS485、I2C和SPI的介绍
Shell 实现文件基本操作(sed-编辑、awk-匹配)
Logback configuration file
Attributeerror: 'tuple' object has no attribute 'layer' problem solving
使用jenkins之二Job
随机推荐
机器学习:numpy版本线性回归预测波士顿房价
【AutoSAR 五 方法论】
[MCU project training] eight way answering machine
AttributeError: ‘tuple‘ object has no attribute ‘layer‘问题解决
Is there a free text to speech tool to help recommend?
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
NC24840 [USACO 2009 Mar S]Look Up
Multiprocess programming (II): Pipeline
Baidu AI Cloud takes the lead in building a comprehensive and standardized platform for smart cloud
[golang syntax] map common errors golang panic: assignment to entry in nil map
简单聊聊运维监控的其他用途
关于XML一些介绍和注意事项
University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
关于QByteArray存储十六进制 与十六进制互转
文件操作IO-Part2
File operation io-part2
Array common operation methods sorting (including ES6) and detailed use
Multiprocess programming (4): shared memory
MySQL 23道经典面试吊打面试官
Why is the website slow to open?