Skip to content

Commit

Permalink
add: 最长交替子数组
Browse files Browse the repository at this point in the history
  • Loading branch information
yi-ge committed Jan 23, 2024
1 parent b5934f4 commit e632bc4
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 1 deletion.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文

### 数组/队列/集合/映射

- [最长交替子数组](src/array/longest_alternating_subarray.cpp) [数组, 枚举]

- LeetCode 2765. 最长交替子数组 <https://leetcode.cn/problems/longest-alternating-subarray>

- [分割数组的最大值](src/array/split_array_largest_sum.cpp) [贪心, 数组, 二分查找, 动态规划, 前缀和]

- LeetCode 410. 分割数组的最大值 <https://leetcode.cn/problems/split-array-largest-sum>
Expand Down
Binary file added images/array/longest_alternating_subarray.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 24 additions & 0 deletions src/array/longest_alternating_subarray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// 最长交替子数组
// https://leetcode.cn/problems/longest-alternating-subarray
// INLINE ../../images/array/longest_alternating_subarray.jpeg

#include <headers.hpp>

class Solution {
public:
int alternatingSubarray(vector<int> &nums) {
int res = -1;
int n = nums.size();
for (int firstIndex = 0; firstIndex < n; firstIndex++) {
for (int i = firstIndex + 1; i < n; i++) {
int length = i - firstIndex + 1;
if (nums[i] - nums[firstIndex] == (length - 1) % 2) {
res = max(res, length);
} else {
break;
}
}
}
return res;
}
};
19 changes: 19 additions & 0 deletions test/array/longest_alternating_subarray_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#include <array/longest_alternating_subarray.cpp>

TEST(最长交替子数组, alternatingSubarray) {
Solution solution;
// 示例 1:
// 输入:nums = [2,3,4,3,4]
// 输出:4
// 解释:交替子数组有 [3,4] ,[3,4,3] 和 [3,4,3,4] 。最长的子数组为 [3,4,3,4]
// ,长度为4 。
vector<int> nums = {2, 3, 4, 3, 4};
EXPECT_EQ(solution.alternatingSubarray(nums), 4);

// 示例 2:
// 输入:nums = [4,5,6]
// 输出:2
// 解释:[4,5] 和 [5,6] 是仅有的两个交替子数组。它们长度都为 2 。
nums = {4, 5, 6};
EXPECT_EQ(solution.alternatingSubarray(nums), 2);
}
2 changes: 1 addition & 1 deletion test/lib/lib_test.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// 执行编译时间:2024-01-21 14:50:51
// 执行编译时间:2024-01-23 10:16:33
#include <gtest/gtest.h>
#include <lib.hpp>

Expand Down

0 comments on commit e632bc4

Please sign in to comment.