|
1 | 1 | // https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away
|
2 |
| -// |
| 2 | +// |
3 | 3 | // Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
|
4 |
| -// |
| 4 | +// |
5 | 5 | // **Example 1:**
|
6 |
| -// |
| 6 | +// |
7 | 7 | // 
|
8 | 8 | // ```
|
9 | 9 | // **Input:** nums = [1,0,0,0,1,0,0,1], k = 2
|
10 | 10 | // **Output:** true
|
11 | 11 | // **Explanation:** Each of the 1s are at least 2 places away from each other.
|
12 | 12 | // ```
|
13 |
| -// |
| 13 | +// |
14 | 14 | // **Example 2:**
|
15 |
| -// |
| 15 | +// |
16 | 16 | // 
|
17 | 17 | // ```
|
18 | 18 | // **Input:** nums = [1,0,0,1,0,1], k = 2
|
19 | 19 | // **Output:** false
|
20 | 20 | // **Explanation:** The second 1 and third 1 are only one apart from each other.
|
21 | 21 | // ```
|
22 |
| -// |
| 22 | +// |
23 | 23 | // **Constraints:**
|
24 |
| -// |
| 24 | +// |
25 | 25 | // * `1 <= nums.length <= 10<sup>5</sup>`
|
26 | 26 | // * `0 <= k <= nums.length`
|
27 | 27 | // * `nums[i]` is `0` or `1`
|
28 | 28 |
|
29 | 29 | pub fn k_length_apart(nums: Vec<i32>, k: i32) -> bool {
|
30 |
| - |
| 30 | + let mut start_index = -k - 1; |
| 31 | + for i in 0..nums.len() { |
| 32 | + if nums[i] == 1 { |
| 33 | + if i as i32 - start_index - 1 < k { |
| 34 | + return false; |
| 35 | + } |
| 36 | + start_index = i as i32; |
| 37 | + } |
31 | 38 | }
|
| 39 | + return true; |
| 40 | +} |
32 | 41 |
|
33 | 42 | #[test]
|
34 | 43 | pub fn t1() {
|
| 44 | + assert_eq!(k_length_apart(vec![1, 0, 0, 0, 1, 0, 0, 1], 2), true); |
| 45 | + assert_eq!(k_length_apart(vec![1, 0, 0, 1, 0, 1], 2), false); |
35 | 46 | }
|
0 commit comments