LeetCode 题解工作台

是否所有 1 都至少相隔 k 个元素

给你一个由若干 0 和 1 组成的数组 nums 以及整数 k 。如果所有 1 都至少相隔 k 个元素,则返回 true ;否则,返回 false 。 示例 1: 输入: nums = [1,0,0,0,1,0,0,1], k = 2 输出: true 解释: 每个 1 都至少相隔 2 个元素。 示…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们可以遍历数组 ,用变量 记录上一个 的下标,那么当前位置 的元素为 时,只需要判断 $i - j - 1$ 是否小于 即可。如果小于 ,则说明存在两个 之间的 的个数小于 ,返回 ;否则,将 更新为 ,继续遍历数组。 遍历结束后,返回 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由若干 01 组成的数组 nums 以及整数 k。如果所有 1 都至少相隔 k 个元素,则返回 true ;否则,返回 false

 

示例 1:

输入:nums = [1,0,0,0,1,0,0,1], k = 2
输出:true
解释:每个 1 都至少相隔 2 个元素。

示例 2:

输入:nums = [1,0,0,1,0,1], k = 2
输出:false
解释:第二个 1 和第三个 1 之间只隔了 1 个元素。

 

提示:

  • 1 <= nums.length <= 105
  • 0 <= k <= nums.length
  • nums[i] 的值为 01
lightbulb

解题思路

方法一:模拟

我们可以遍历数组 nums\textit{nums},用变量 jj 记录上一个 11 的下标,那么当前位置 ii 的元素为 11 时,只需要判断 ij1i - j - 1 是否小于 kk 即可。如果小于 kk,则说明存在两个 11 之间的 00 的个数小于 kk,返回 false\text{false};否则,将 jj 更新为 ii,继续遍历数组。

遍历结束后,返回 true\text{true}

时间复杂度 O(n)O(n),其中 nn 为数组 nums\textit{nums} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
class Solution:
    def kLengthApart(self, nums: List[int], k: int) -> bool:
        j = -inf
        for i, x in enumerate(nums):
            if x:
                if i - j - 1 < k:
                    return False
                j = i
        return True
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate correctly identifies an array-driven approach.

  • question_mark

    The candidate is able to identify and handle early termination to optimize performance.

  • question_mark

    The candidate does not attempt overly complex solutions when a simpler approach works well.

warning

常见陷阱

外企场景
  • error

    Not handling the case where there are fewer than two 1's in the array, which should immediately return true.

  • error

    Assuming the array always has two 1's or more without checking edge cases.

  • error

    Failing to exit early when the distance condition is violated, leading to unnecessary checks.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Change the problem to check for a different minimum distance between 1's.

  • arrow_right_alt

    Allow the array to be a circular buffer where the first and last 1 can be considered neighbors.

  • arrow_right_alt

    Add multiple values for k and return an array of boolean results for each value.

help

常见问题

外企场景

是否所有 1 都至少相隔 k 个元素题解:数组·driven | LeetCode #1437 简单