zoukankan      html  css  js  c++  java
  • 【leetcode】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.

    Example 1:

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

    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.

    Example 3:

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

    Example 4:

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

    Constraints:

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

    解题思路:感觉本题难度应该是Easy而不是Medium。

    代码如下:

    class Solution(object):
        def kLengthApart(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: bool
            """
            last_one = None
            for i in range(len(nums)):
                if nums[i] == 1 and last_one == None:
                    last_one = i
                elif nums[i] == 1 and last_one != None:
                    if i - last_one - 1 < k:
                        return False
                    last_one = i
            return True
  • 相关阅读:
    Maven 安装配置
    docker 安装 MySQL
    查看CentOS版本方法
    JavaScript定时器的开启关闭
    JavaScript实现延时提示框
    JavaScript获取当前时间
    JavaScript实现数字时钟功能
    JavaScript获取非行间样式
    JavaScript数组的操作
    JavaScript数组和json的区别
  • 原文地址:https://www.cnblogs.com/seyjs/p/13041205.html
Copyright © 2011-2022 走看看