资讯专栏INFORMATION COLUMN

[LeetCode] 849. Maximize Distance to Closest Perso

JerryC / 3182人阅读

Problem

In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.

There is at least one empty seat, and at least one person sitting.

Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.

Return that maximum distance to closest person.

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.

Solution
class Solution {
    public int maxDistToClosest(int[] seats) {
        int max = 0, left = -1, len = seats.length;
        for (int i = 0; i < len; i++) {
            if (seats[i] == 1) {
                if (left == -1) max = Math.max(max, i);
                else max = Math.max(max, (i-left)/2);
                left = i;
            }
        }
        if (seats[len-1] == 0) max = Math.max(max, len-1-left);
        return max;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/71956.html

相关文章

  • [LintCode] K Closest Points

    Problem Given some points and a point origin in two dimensional space, find k points out of the some points which are nearest to origin.Return these points sorted by distance, if they are same with di...

    沈俭 评论0 收藏0
  • [Leetcode] Closest Binary Search Tree Value 最近二叉搜索

    摘要:递归法复杂度时间空间思路根据二叉树的性质,我们知道当遍历到某个根节点时,最近的那个节点要么是在子树里面,要么就是根节点本身。因为我们知道离目标数最接近的数肯定在二叉搜索的路径上。 Closest Binary Search Tree Value I Given a non-empty binary search tree and a target value, find the va...

    AlphaWallet 评论0 收藏0
  • Leetcode PHP题解--D29 973. K Closest Points to Origi

    摘要:题目链接题目分析给一个坐标数组,从中返回个离最近的坐标。其中,用欧几里得距离计算。思路把距离作为数组的键,把对应坐标作为数组的值。用函数排序,再用函数获取前个即可。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 973. K Closest Points to Origin 题目链接 973. K Closest Points to Origin 题目分析 给一个坐标数组points...

    Sanchi 评论0 收藏0
  • LeetCode[270] Closest Binary Search Tree Value

    摘要:复杂度思路用一个变量来记录当前的值,并且在每次之前,比较得到目前的最大值。注意变量的比较不要用代码 LeetCode[270] Closest Binary Search Tree Value Given a non-empty binary search tree and a target value, find the value in the BST that is close...

    pumpkin9 评论0 收藏0
  • leetcode16 3Sum Closest

    摘要:返回这三个值的和。思路一三指针这里的思路和是一样的,就是用三个指针获得三个值并计算他们的和。 题外话 鉴于这一题的核心思路和leetcode15的思路相同,可以先写一下15题并参考一下我之前的一篇博客 题目要求 Given an array S of n integers, find three integers in S such that the sum is closest to...

    Blackjun 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<