LeetCode 1437 Check If All 1's Are at Least Length K Places Away (Python)

Posted by 小明MaxMing on January 25, 2021

题目

Given an array nums of 0s and 1s and an integer k, return True if all 1’s are at least k places away from each other, otherwise return False.

解题思路

遍历数组,遇到1计算距上一个1出现的距离

代码

class Solution:
    def kLengthApart(self, nums: List[int], k: int) -> bool:
        ct = k
        for n in nums:
            if n:
                if ct < k:
                    return False
                ct = 0
            else:
                ct += 1
        return True

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅