leetcode算法题--最长奇偶子数组

原题链接:https://leetcode.cn/problems/longest-even-odd-subarray-with-threshold/

一开始的做法,是O(n*n)的时间复杂度

func longestAlternatingSubarray(nums []int, threshold int) int {
    n := len(nums)
    res := 0 
    for i := 0; i < n; i ++ {
        if nums[i] % 2 != 0 || nums[i] > threshold {
           continue 
        } 
        dis := 1 
        res = max(res, dis)     
        for j := i + 1; j < n; j++ {
            if nums[j] > threshold || nums[j - 1] % 2 == nums[j] % 2 {
                break
            }
            dis = j - i + 1
            res = max(res, dis)     
        } 
    }
    return res
}

func max(a, b int) int {
    if a > b {
        return a
    }
    
    return b
}

但这里其实是有一个优化的点,因为其实这些子数组是不会相互重叠的,所以我们可以优化外层循环,直接将i移到j的下一个位置,这种类型可以称为分组循环,时间复杂度是O(n)

func longestAlternatingSubarray(nums []int, threshold int) int {
    n := len(nums)
    res := 0 
    for i := 0; i < n; i++ {
        if nums[i] % 2 != 0 || nums[i] > threshold {
           continue 
        } 
        dis := 1 
        res = max(res, dis)     
        start := i 
        for j := i + 1; j < n; j++ {
            if nums[j] > threshold || nums[j - 1] % 2 == nums[j] % 2 {
                break
            }
            dis = j - start + 1
            res = max(res, dis)     
            i = j
        } 
    }
    return res
}

func max(a, b int) int {
    if a > b {
        return a
    }
    
    return b
}

你可能感兴趣的:(Algorithm,算法,leetcode,职场和发展)