Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,11 @@ tags:

### 方法一:模拟

我们可以遍历数组 $nums$,用变量 $j$ 记录上一个 $1$ 的下标,那么当前位置 $i$ 的元素为 $1$ 时,只需要判断 $i - j - 1$ 是否小于 $k$ 即可。如果小于 $k$,则说明存在两个 $1$ 之间的 $0$ 的个数小于 $k$,返回 `false`;否则,将 $j$ 更新为 $i$,继续遍历数组。
我们可以遍历数组 $\textit{nums}$,用变量 $j$ 记录上一个 $1$ 的下标,那么当前位置 $i$ 的元素为 $1$ 时,只需要判断 $i - j - 1$ 是否小于 $k$ 即可。如果小于 $k$,则说明存在两个 $1$ 之间的 $0$ 的个数小于 $k$,返回 $\text{false}$;否则,将 $j$ 更新为 $i$,继续遍历数组。

遍历结束后,返回 `true`
遍历结束后,返回 $\text{true}$

时间复杂度 $O(n)$,其中 $n$ 为数组 $nums$ 的长度。空间复杂度 $O(1)$。
时间复杂度 $O(n)$,其中 $n$ 为数组 $\textit{nums}$ 的长度。空间复杂度 $O(1)$。

<!-- tabs:start -->

Expand Down Expand Up @@ -153,6 +153,25 @@ function kLengthApart(nums: number[], k: number): boolean {
}
```

#### Rust

```rust
impl Solution {
pub fn k_length_apart(nums: Vec<i32>, k: i32) -> bool {
let mut j = -(k + 1);
for (i, &x) in nums.iter().enumerate() {
if x == 1 {
if (i as i32) - j - 1 < k {
return false;
}
j = i as i32;
}
}
true
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,13 @@ tags:

<!-- solution:start -->

### Solution 1
### Solution 1: Simulation

We can iterate through the array $\textit{nums}$ and use a variable $j$ to record the index of the previous $1$. When the element at the current position $i$ is $1$, we just need to check if $i - j - 1$ is less than $k$. If it is less than $k$, it means there exists a pair of $1$s with fewer than $k$ zeros between them, so we return $\text{false}$. Otherwise, we update $j$ to $i$ and continue iterating through the array.

After the iteration is complete, we return $\text{true}$.

The time complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. The space complexity is $O(1)$.

<!-- tabs:start -->

Expand Down Expand Up @@ -143,6 +149,25 @@ function kLengthApart(nums: number[], k: number): boolean {
}
```

#### Rust

```rust
impl Solution {
pub fn k_length_apart(nums: Vec<i32>, k: i32) -> bool {
let mut j = -(k + 1);
for (i, &x) in nums.iter().enumerate() {
if x == 1 {
if (i as i32) - j - 1 < k {
return false;
}
j = i as i32;
}
}
true
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
impl Solution {
pub fn k_length_apart(nums: Vec<i32>, k: i32) -> bool {
let mut j = -(k + 1);
for (i, &x) in nums.iter().enumerate() {
if x == 1 {
if (i as i32) - j - 1 < k {
return false;
}
j = i as i32;
}
}
true
}
}