1437. Check If All 1's Are at Least Length K Places Away

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.

给一个数组,里面全是0和1,问是否所有的1和临近的1直接的距离不小于k

就记录上一次的1的index,然后和下一次的比看看距离

class Solution(object):
    def kLengthApart(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        last_index = -k - 1
        for i in range(0, len(nums), 1):
            if nums[i] == 1:
                if i - last_index - 1 < k:
                    return False
                last_index = i
        return True
                    

 

posted @ 2020-07-22 13:43  whatyouthink  阅读(87)  评论(0编辑  收藏  举报