【每日一题】最长交替子数组

文章目录

Tag

【双层循环】【单层循环】【数组】【2024-01-23】


题目来源

2765. 最长交替子数组


解题思路

两个方法,一个是双层循环,一个是单层循环。

方法一:双层循环

思路

第一层枚举子数组的起点,第二层从起点的下一个元素开始枚举,判断接下来的字符是否满足交替子数组的条件。如是则更新长度,否则调出内层循环。

算法

cpp 复制代码
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;
    }
};

复杂度分析

时间复杂度: O ( n 2 ) O(n^2) O(n2), n n n 为数组 nums 的长度。

空间复杂度: O ( 1 ) O(1) O(1)。

方法二:单层循环

思路

解题思路参考 教你一次性把代码写对!O(n) 分组循环(Python/Java/C++/Go/JS/Rust)

算法

cpp 复制代码
class Solution {
public:
    int alternatingSubarray(vector<int> &nums) {
        int ans = -1;
        int i = 0, n = nums.size();
        while (i < n - 1) {
            if (nums[i + 1] - nums[i] != 1) {
                i++; // 直接跳过
                continue;
            }
            int i0 = i; // 记录这一组的开始位置
            i += 2; // i 和 i+1 已经满足要求,从 i+2 开始判断
            while (i < n && nums[i] == nums[i0] + (i - i0) % 2) {
                i++;
            }
            // 从 i0 到 i-1 是满足题目要求的(并且无法再延长的)子数组
            ans = max(ans, i - i0);
            i--;
        }
        return ans;
    }
};

复杂度分析

时间复杂度: O ( n ) O(n) O(n), n n n 为数组 nums 的长度。

空间复杂度: O ( 1 ) O(1) O(1)。


写在最后

如果您发现文章有任何错误或者对文章有任何疑问,欢迎私信博主或者在评论区指出 💬💬💬。

如果大家有更优的时间、空间复杂度的方法,欢迎评论区交流。

最后,感谢您的阅读,如果有所收获的话可以给我点一个 👍 哦。

相关推荐
2401_841495644 天前
【LeetCode刷题】找到字符串中所有字母异位词
数据结构·python·算法·leetcode·数组·滑动窗口·找到字符串中所有字母异位词
alwaysrun7 天前
Rust中数组简介
rust·数组·array·切片
2401_841495649 天前
【LeetCode刷题】移动零
数据结构·python·算法·leetcode·数组·双指针法·移动零
暴风鱼划水10 天前
算法题(Python)数组篇 | 6.区间和
python·算法·数组·区间和
課代表11 天前
VB.Net 常用函数
字符串·类型转换·数组·函数·vb.net·日期时间·条件
課代表11 天前
JavaScript 中获取二维数组最大值
javascript·max·数组·递归·array·最大值·二维
SamHou012 天前
奶奶都能看懂的 C++ —— 数组与指针
指针·数组·cpp
苏纪云24 天前
数据结构<C++>——数组
java·数据结构·c++·数组·动态数组
云计算练习生1 个月前
linux shell编程实战 03 数组:批量处理数据
linux·运维·服务器·数组·shell编程
w_w方圆1 个月前
1.序列式容器-vector&list
链表·stl·vector·数组·标准模板库