2760.最长奇偶子数组
链接:2760.最长奇偶子数组
难度:Easy
标签:数组、滑动窗口
简介:给你一个下标从 0 开始的整数数组 nums 和一个整数 threshold 。以整数形式返回满足题目要求的最长子数组的长度。
题解 1 - cpp
- 编辑时间:2023-07-02
- 执行用时:104ms
- 内存消耗:88.9MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    int longestAlternatingSubarray(vector<int>& nums, int threshold) {
        int n = nums.size(), res = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] % 2 != 0 || nums[i] > threshold) continue;
            int cnt = 1;
            for (int j = i + 1; j < n; j++) {
                if (nums[j] % 2 == nums[j - 1] % 2 || nums[j] > threshold) break;
                cnt++;
            }
            res = max(res, cnt);
        }
        return res;
    }
};
题解 2 - python
- 编辑时间:2023-07-02
- 执行用时:296ms
- 内存消耗:16.1MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int:
        n = len(nums)
        res = 0
        for i in range(n):
            if nums[i] % 2 != 0 or nums[i] > threshold:
                continue
            cnt = 1
            for j in range(i+1, n):
                if nums[j] % 2 == nums[j-1] % 2 or nums[j] > threshold:
                    break
                cnt += 1
            res = max(res, cnt)
        return res
题解 3 - python
- 编辑时间:2023-11-16
- 执行用时:96ms
- 内存消耗:15.67MB
- 编程语言:python
- 解法介绍:遍历。
class Solution:
    def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int:
        n = len(nums)
        i = 0
        ans = 0
        while i < n:
            if nums[i] <= threshold and nums[i] % 2 == 0:
                start = i
                while i + 1 < n and nums[i + 1] % 2 != nums[i] % 2 and nums[i + 1] <= threshold:
                    i += 1
                ans = max(ans, i - start + 1)
            i += 1
        return ans
题解 4 - rust
- 编辑时间:2023-07-02
- 执行用时:12ms
- 内存消耗:1.9MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn longest_alternating_subarray(nums: Vec<i32>, threshold: i32) -> i32 {
        let n = nums.len();
        let mut res = 0;
        for i in 0..n {
            if nums[i] % 2 != 0 || nums[i] > threshold {
                continue;
            }
            let mut cnt = 1;
            for j in i + 1..n {
                if nums[j] % 2 == nums[j - 1] % 2 || nums[j] > threshold {
                    break;
                }
                cnt += 1;
            }
            res = res.max(cnt);
        }
        res
    }
}