1437. Check If All 1's Are at Least Length K Places Away
leetcode easy
#array#csharp#easy#leetcode
Task
Дан бинарный массив nums и целое число k. Вернуть true, если все единицы находятся на расстоянии не менее k позиций друг от друга, в противном случае вернуть false.
Пример:
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.
C# solution
matched/originalpublic class Solution {
public bool KLengthApart(int[] nums, int k) {
int count = k;
foreach (int num in nums) {
if (num == 1) {
if (count < k) {
return false;
}
count = 0;
} else {
count++;
}
}
return true;
}
}C++ solution
auto-draft, review before submit#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public bool KLengthApart(vector<int>& nums, int k) {
int count = k;
foreach (int num in nums) {
if (num == 1) {
if (count < k) {
return false;
}
count = 0;
} else {
count++;
}
}
return true;
}
}Java solution
matched/originalclass Solution {
public boolean kLengthApart(int[] nums, int k) {
int count = k;
for (int num : nums) {
if (num == 1) {
if (count < k) {
return false;
}
count = 0;
} else {
count++;
}
}
return true;
}
}JavaScript solution
matched/originalclass Solution {
kLengthApart(nums, k) {
let count = k;
for (const num of nums) {
if (num === 1) {
if (count < k) {
return false;
}
count = 0;
} else {
count++;
}
}
return true;
}
}Python solution
matched/originalclass Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
count = k
for num in nums:
if num == 1:
if count < k:
return False
count = 0
else:
count += 1
return TrueExplanation
Algorithm
Инициализировать счетчик нулей значением k для учета первого появления единицы.
Итерировать по массиву nums, проверяя, если текущий элемент равен 1. Если число нулей между единицами меньше k, вернуть false; иначе сбросить счетчик нулей на 0.
Если текущий элемент равен 0, увеличить счетчик нулей. В конце итерации вернуть true.
😎