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

相关推荐
ShineWinsu18 小时前
对于C++:类和对象的解析—下(第二部分)
c++·面试·笔试·对象··工作·stati
如何原谅奋力过但无声19 小时前
【力扣-Python-滑动窗口经典题】567.字符串的排列 | 424.替换后的最长重复字符 | 76.最小覆盖子串
算法·leetcode
BHXDML20 小时前
第七章:类与对象(c++)
开发语言·c++
52Hz11820 小时前
力扣73.矩阵置零、54.螺旋矩阵、48.旋转图像
python·算法·leetcode·矩阵
yyf1989052520 小时前
C++ 跨平台开发的挑战与应对策略
c++
iAkuya20 小时前
(leetcode)力扣100 二叉搜索树种第K小的元素(中序遍历||记录子树的节点数)
算法·leetcode·职场和发展
又见野草21 小时前
C++类和对象(中)
开发语言·c++
Remember_99321 小时前
【LeetCode精选算法】滑动窗口专题二
java·开发语言·数据结构·算法·leetcode
hellokandy1 天前
C++ 如何知道程序最多可以申请多少内存
c++·vector·cin·cout
圣保罗的大教堂1 天前
leetcode 1895. 最大的幻方 中等
leetcode