给你一个由若干 0
和 1
组成的数组 nums
以及整数 k
。如果所有 1
都至少相隔 k
个元素,则返回 True
;否则,返回 False
。
1437. 是否所有 1 都至少相隔 k 个元素 – 力扣(Leetcode)


思路:
找1之间的间隔就行了。
python3实现:
class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
# 找到所有1的间隔
# 去掉特殊情况
if 1 not in nums:
return True
p = 0
list_1 = []
tmp = nums.index(1)
p = nums.index(1)+1
while p <= len(nums) - 1:
if nums[p] == 1:
list_1.append(p - tmp - 1)
tmp = p
p += 1
# print("list_1:", list_1)
if len(list_1) == 0 and k != 0:
return True
if min(list_1) < k:
return False
return True
