This is the fifth day of my participation in the August Wen Challenge.More challenges in August

describe

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.

Example 1:

Input: nums = [1,0,0, 1,0,0,1], k = 2 Output: true Explanation: Each of the 1s are at least 2 places away from each other.Copy the code

Example 2:

Input: nums = [1,0,0,1,0,1], k = 2
Output: false
Explanation: The second 1 and third 1 are only one apart from each other.
Copy the code

Example 3:

Input: nums = [1,1,1,1,1], k = 0
Output: true
Copy the code

Example 4:

Input: nums = [0,1,0,1], k = 1
Output: true
Copy the code

Note:

1 <= nums.length <= 10^5
0 <= k <= nums.length
nums[i] is 0 or 1
Copy the code

parsing

1 in nums has at least k zeros in it. When nums are all zeros or only one nums, this is True. Nums = 1, k = 1, k = 1, k = 1, k = 1

answer

class Solution(object):
    def kLengthApart(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        if sum(nums)<=1:
            return True
        start = nums.index(1)
        end = nums.index(1,start+1)
        if end-start<k+1:
            return False
        index = end+1
        while index<len(nums):
            if nums[index]==1:
                if index-end<k+1:
                    return False
                end = index
            index += 1
        return True
        	      
		
Copy the code

The results

Runtime: 468 ms, Faster than 95.71% of Python online submissions for Check If All 1's Are at Least Length K Places Away. Memory Usage: The linked submissions in the Python online list for Check If All 1's Are at Least Length K Places Away.Copy the code

parsing

The above code is actually quite messy, I sorted it out, the principle is the same as above, more concise and easy to understand.

answer

class Solution(object):
    def kLengthApart(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        count = k
        for num in nums:
            if num == 1:
                if count < k:
                    return False
                count = 0
            else:
                count += 1
        return True



        	      
		
Copy the code

The results

Runtime: 468 ms, Faster than 91.23% of Python online submissions for Check If All 1's Are at Least Length K Places Away. Memory Usage: The linked submissions in the Python online list for Check If All 1's Are at Least Length K Places Away.Copy the code

Original link: leetcode.com/problems/ch…

Your support is my biggest motivation