LeetCode 1989. 捉迷藏中可捕获的最大人数

1989. 捉迷藏中可捕获的最大人数

你正在和你的朋友玩捉迷藏游戏。在捉迷藏比赛中,人们被分成两组:是 “鬼” 的人,和不是 “鬼” 的人。是 “鬼” 的人想要抓住尽可能多的不是 “鬼” 的人。

给定一个 从 0 开始建立索引 的整数数组 team,其中只包含 0 (表示 不是 “鬼” 的人) 和 1 (表示是 “鬼” 的人),以及一个整数 dist。索引 i 为 “鬼” 的人可以捕获索引在 [i - dist, i + dist](包括) 范围内且 不是 “鬼” 的任何一个人。

返回 “鬼” 所能捕获的最大人数

示例 1:

输入: team = [0,1,0,1,0], dist = 3
输出: 2
解释:
在索引 1 的 “鬼” 可以捕获范围 [i-dist, i+dist] = [1-3, 1+3] = [-2, 4] 内的人。
他们可以抓住索引 2 中不是 “鬼” 的人。
在索引 3 的 “鬼” 可以捕获范围 [i-dist, i+dist] = [3-3, 3+3] = [0, 6] 内的人。
他们可以抓住索引 0 中不是 “鬼” 的人。
在索引 4 上不是 “鬼” 的人不会被抓住,因为在索引 1 和 3 上的人已经抓住了一个人。

示例 2:

输入: team = [1], dist = 1
输出: 0
解释:
没有 “鬼" 要抓的人。

示例 3:

输入: team = [0], dist = 1
输出: 0
解释:
没有 “鬼” 来抓人。

提示:

  • 1 <= team.length <= 10^5
  • 0 <= team[i] <= 1
  • 1 <= dist <= team.length

提示 1

Try to use as much of the range of a person who is "it" as possible.


提示 2

Find the leftmost person who is "it" that has not caught anyone yet, and the leftmost person who is not "it" that has not been caught yet.


提示 3

If the person who is not "it" can be caught, pair them together and repeat the process.


提示 4

If the person who is not "it" cannot be caught, and the person who is not "it" is on the left of the person who is "it", find the next leftmost person who is not "it".


提示 5

If the person who is not "it" cannot be caught, and the person who is "it" is on the left of the person who is not "it", find the next leftmost person who is "it".

解法:

0是人,1是鬼👻,👻1在半径为 dist 的范围内 抓 0,每个👻1最多只能抓1个0,0被抓后就没了。

所以每个 👻1 尽量抓 左边的 0,这样抓完后,不影响后面的👻 1 继续抓 0 。

从左到右遍历👻 1,每次都抓他能遇见的最左边的 0。用双指针,right 表示 👻 1, left 表示最左边的 0,抓完一个人,双双向右平移一格。因为👻1 有抓人的范围,因此每次能抓 0的位置是有限制的.

类似题型:

LeetCode 2086. 喂食仓鼠的最小食物桶数-CSDN博客

class Solution {
    public int catchMaximumAmountofPeople(int[] team, int dist) {
        int ans = 0;
        int left = 0;
        for (int right = 0; right < team.length; right++) {
            if (team[right] == 0) {
                continue;
            }
            // left 起点:取 上一次的位置 和 抓人范围左端点 的最大值
            left = Math.max(left, right - dist);
            while (left < team.length && left <= right + dist && team[left] == 1) {
                left++;
            }
            if (left < team.length && left <= right + dist) {
                ans++;
                left++;
            }
        }
        return ans;
    }
}

 复杂度分析 

  • 时间复杂度:O(n),n 是 数组 nums 的长度。
  • 空间复杂度:O(1)。

 

 

  • 13
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值