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

文章目录

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)。


写在最后

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

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

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

相关推荐
c++初学者ABC7 天前
【例51.3】 平移数据
c++·数组
Tisfy12 天前
LeetCode 2239.找到最接近 0 的数字:遍历
算法·leetcode·题解·数组·遍历
AQin101223 天前
【Leetcode·中等·数组】59. 螺旋矩阵 II(spiral matrix ii)
算法·leetcode·矩阵·数组
WeeJot嵌入式1 个月前
C语言----数组
c语言·数组
Amd7941 个月前
特殊数据类型的深度分析:JSON、数组和 HSTORE 的实用价值
postgresql·json·数据存储·数据类型·数组·日期和时间·hstore
DogDaoDao1 个月前
leetcode 面试经典 150 题:删除有序数组中的重复项
算法·leetcode·面试·数组·双指针·数据结构与算法·重复数组
A懿轩A1 个月前
C/C++ 数据结构与算法【数组】 数组详细解析【日常学习,考研必备】带图+详细代码
c语言·数据结构·c++·学习·考研·算法·数组
Moshow郑锴1 个月前
Spring Boot中CollectionUtils怎么用
springboot·数组·collectionutil
LuckyLay1 个月前
Golang学习笔记_13——数组
笔记·学习·golang·数组·array
暂时先用这个名字2 个月前
PHP开发日志 ━━ 基础知识:四种不同的变量返回方式该如何调用
android·开发语言·缓存·php·框架·变量·数组