【leetcode】1437. Check If All 1's Are at Least Length K Places Away
题目如下:
Given an array
nums
of 0s and 1s and an integerk
, returnTrue
if all 1's are at leastk
places away from each other, otherwise returnFalse
.
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: trueExample 4:
Input: nums = [0,1,0,1], k = 1 Output: trueConstraints:
1 <= nums.length <= 10^5
0 <= k <= nums.length
nums[i]
is0
or1
解题思路:感觉本题难度应该是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