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 个元素。 示…
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们可以遍历数组 ,用变量 记录上一个 的下标,那么当前位置 的元素为 时,只需要判断 $i - j - 1$ 是否小于 即可。如果小于 ,则说明存在两个 之间的 的个数小于 ,返回 ;否则,将 更新为 ,继续遍历数组。 遍历结束后,返回 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个由若干 0 和 1 组成的数组 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 <= 1050 <= k <= nums.lengthnums[i]的值为0或1
解题思路
方法一:模拟
我们可以遍历数组 ,用变量 记录上一个 的下标,那么当前位置 的元素为 时,只需要判断 是否小于 即可。如果小于 ,则说明存在两个 之间的 的个数小于 ,返回 ;否则,将 更新为 ,继续遍历数组。
遍历结束后,返回 。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.