Leetcode2760. 最长奇偶子数组

Every day a Leetcode

题目来源:2760. 最长奇偶子数组

解法1:模拟

代码:

c 复制代码
class Solution
{
public:
    int longestAlternatingSubarray(vector<int> &nums, int threshold)
    {
        int n = nums.size();
        int ans = 0;
        for (int i = 0; i < n; i++)
        {
            if (nums[i] % 2 != 0 || nums[i] > threshold)
                continue;
            int left = i, right = i;
            for (int j = i + 1; j < n; j++)
            {
                if (nums[j - 1] % 2 != nums[j] % 2 && nums[j] <= threshold)
                    right++;
                else
                    break;
            }
            ans = max(right - left + 1, ans);
        }
        return ans;
    }
};

结果:

复杂度分析:

时间复杂度:O(n2),其中 n 是数组 nums 的长度。

空间复杂度:O(1)。

相关推荐
June bug30 分钟前
(#字符串处理)字符串中第一个不重复的字母
python·leetcode·面试·职场和发展·跳槽
jojo_zjx1 小时前
GESP 24年12月2级 数位和
c++
自由的好好干活1 小时前
PCI9x5x驱动移植支持PCI9054在win7下使用3
c++·驱动开发
AlenTech1 小时前
197. 上升的温度 - 力扣(LeetCode)
算法·leetcode·职场和发展
源代码•宸3 小时前
Leetcode—404. 左叶子之和【简单】
经验分享·后端·算法·leetcode·职场和发展·golang·dfs
WBluuue3 小时前
数据结构与算法:dp优化——优化尝试和状态设计
c++·算法·leetcode·动态规划
im_AMBER3 小时前
Leetcode 105 K 个一组翻转链表
数据结构·学习·算法·leetcode·链表
sin_hielo3 小时前
leetcode 1877
数据结构·算法·leetcode
睡不醒的kun3 小时前
定长滑动窗口-基础篇(2)
数据结构·c++·算法·leetcode·职场和发展·滑动窗口·定长滑动窗口
小王努力学编程3 小时前
LangChain——AI应用开发框架(核心组件1)
linux·服务器·前端·数据库·c++·人工智能·langchain