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

相关推荐
汉克老师几秒前
GESP2025年9月认证C++三级真题与解析(单选题9-15)
c++·算法·数组·string·字符数组·gesp三级·gesp3级
MLGDOU1 分钟前
Chatsdk模型接口的设计
网络·c++
平生不喜凡桃李4 分钟前
LeetCode:LRU and LFU
算法·leetcode·哈希算法
编程大师哥12 分钟前
如何在C++中使用Redis的事务功能?
开发语言·c++·redis
朔北之忘 Clancy31 分钟前
第二章 分支结构程序设计(1)
c++·算法·青少年编程·竞赛·教材·考级·讲义
汉克老师43 分钟前
GESP2025年9月认证C++二级真题与解析(编程题2(菱形))
c++·找规律·二维数组·枚举算法·曼哈顿距离·模拟画图
君义_noip1 小时前
信息学奥赛一本通 1528:【例 2】单词游戏
c++·算法·信息学奥赛·一本通·csp-s
AlenTech1 小时前
238. 除了自身以外数组的乘积 - 力扣(LeetCode)
算法·leetcode·职场和发展
FL16238631291 小时前
[C++][cmake]基于C++在windows上部署yolo26的目标检测onnx模型
c++·windows·目标检测
朔北之忘 Clancy1 小时前
第一章 顺序结构程序设计(1)
c++·算法·青少年编程·竞赛·教材·考级·讲义