diff --git a/README.md b/README.md index 7784219..d1d66b5 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,10 @@ Rust标准库`std::collections`提供了4种通用容器类型,包含一下8 ### 数组/队列/集合/映射 +- [最长交替子数组](src/array/longest_alternating_subarray.rs) [数组, 枚举] + + - LeetCode 2765. 最长交替子数组 + - [分割数组的最大值](src/array/split_array_largest_sum.rs) [贪心, 数组, 二分查找, 动态规划, 前缀和] - LeetCode 410. 分割数组的最大值 diff --git a/images/array/longest_alternating_subarray.jpeg b/images/array/longest_alternating_subarray.jpeg new file mode 100644 index 0000000..3d0e425 Binary files /dev/null and b/images/array/longest_alternating_subarray.jpeg differ diff --git a/src/array/longest_alternating_subarray.rs b/src/array/longest_alternating_subarray.rs new file mode 100644 index 0000000..2937b60 --- /dev/null +++ b/src/array/longest_alternating_subarray.rs @@ -0,0 +1,25 @@ +// 最长交替子数组 +// https://leetcode.cn/problems/longest-alternating-subarray +// INLINE ../../images/array/longest_alternating_subarray.jpeg + +pub struct Solution; + +impl Solution { + pub fn alternating_subarray(nums: Vec) -> i32 { + let mut res = -1; + let n = nums.len(); + for first_index in 0..n { + for i in (first_index + 1)..n { + let length = i - first_index + 1; + if nums[i] - nums[first_index] + == TryInto::::try_into((length - 1) % 2).unwrap() + { + res = res.max(length as i32); + } else { + break; + } + } + } + res + } +} diff --git a/src/array/mod.rs b/src/array/mod.rs index 6267f81..3307f319 100644 --- a/src/array/mod.rs +++ b/src/array/mod.rs @@ -58,3 +58,4 @@ pub mod count_common_words_with_one_occurrence; pub mod find_maximum_number_of_string_pairs; pub mod split_strings_by_separator; pub mod split_array_largest_sum; +pub mod longest_alternating_subarray; diff --git a/tests/array/longest_alternating_subarray_test.rs b/tests/array/longest_alternating_subarray_test.rs new file mode 100644 index 0000000..45f3ceb --- /dev/null +++ b/tests/array/longest_alternating_subarray_test.rs @@ -0,0 +1,18 @@ +use rust_practice::array::longest_alternating_subarray::Solution; + +#[test] +fn alternating_subarray_test() { + // 示例 1: + // 输入:nums = [2,3,4,3,4] + // 输出:4 + // 解释:交替子数组有 [3,4] ,[3,4,3] 和 [3,4,3,4] 。最长的子数组为 [3,4,3,4] ,长度为4 。 + let nums = vec![2, 3, 4, 3, 4]; + assert_eq!(Solution::alternating_subarray(nums), 4); + + // 示例 2: + // 输入:nums = [4,5,6] + // 输出:2 + // 解释:[4,5] 和 [5,6] 是仅有的两个交替子数组。它们长度都为 2 。 + let nums = vec![4, 5, 6]; + assert_eq!(Solution::alternating_subarray(nums), 2); +} diff --git a/tests/array/mod.rs b/tests/array/mod.rs index 353ca76..48fd3d7 100644 --- a/tests/array/mod.rs +++ b/tests/array/mod.rs @@ -58,3 +58,4 @@ pub mod zero_matrix_lcci_test; pub mod find_maximum_number_of_string_pairs_test; pub mod split_strings_by_separator_test; pub mod split_array_largest_sum_test; +pub mod longest_alternating_subarray_test;