当前位置:网站首页>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});//选择最大值
}
};
边栏推荐
- Tensorflow 2. Chapter 15 of X (keras) source code explanation: migration learning and fine tuning
- University of Toronto:Anthony Coache | 深度强化学习的条件可诱导动态风险度量
- Pageoffice - bug modification journey
- Cordova plugin device obtains the device information plug-in, which causes Huawei to fail the audit
- 【AutoSAR 三 RTE概述】
- LeedCode1480. Dynamic sum of one-dimensional array
- Andorid gets the system title bar height
- Shell implements basic file operations (SED edit, awk match)
- Leetcode 294. Flip game II (game theory)
- Briefly talk about other uses of operation and maintenance monitoring
猜你喜欢
使用jenkins之二Job
1.11 - bus
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
【AutoSAR 十三 NVM】
AEM: Nanlin fan Ben et al. - plant rhizosphere growth promoting bacteria control soybean blight
University of Toronto:Anthony Coache | 深度强化学习的条件可诱导动态风险度量
【AutoSAR 十一 通信相关机制】
1.12 - 指令
DotNet圈里一个优秀的ORM——FreeSql
Markdown tutorial
随机推荐
Multiprocess programming (V): semaphores
AEM: Nanlin fan Ben et al. - plant rhizosphere growth promoting bacteria control soybean blight
Centos7 one click compilation to build MySQL script
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
Vulkan并非“灵药“
Markdown tutorial
百度智能云牵头打造智能云综合标准化平台
字符设备注册常用的两种方法和步骤
Extension of flutter
Gan model architecture in mm
Multiprocess programming (II): Pipeline
Automated defect analysis in electronic microscopic images
Introduction and use of ftrace tool
Vulkan performance and refinement
多进程编程(一):基本概念
Rust ownership (very important)
NC50528 滑动窗口
【JetCache】JetCache的配置说明和注解属性说明
【AutoSAR 三 RTE概述】
使用jenkins之二Job