leetcode-187周赛-5402-绝对值差不超过限制的最长连续子数组

题目描述:

 

 第一次提交:

class Solution:
    def longestSubarray(self, nums, limit: int) -> int:
        res = 0
        i,j = 0,0
        n = len(nums)
        l = [[nums[0],0],[nums[0],0]]
        while i + res < n:
            while j < n and l[1][0] - l[0][0] <= limit:
                if j == 28:
                    print(nums[j])
                res = max(res, j - i + 1)
                j += 1
                if j == n:break
                if nums[j] <= l[0][0]: l[0] = [nums[j],j]
                if nums[j] >= l[1][0]: l[1] = [nums[j],j]
            if j == n:
                break
            if l[1][0] == nums[j] :
                i = l[0][1] + 1
                l = [[nums[i], i], [nums[i], i]]
                j = i
            else :
                i = l[1][1] + 1
                l = [[nums[i], i], [nums[i], i]]
                j = i

        return res

优化:堆+滑动窗口

class Solution:
    def longestSubarray(self, nums: List[int], limit: int) -> int:
        from heapq import heappop, heappush
        max_ = []
        min_ = []
        res = 0
        l = 0
        for r, num in enumerate(nums):
            # 大根堆 max_
            heappush(max_, [-num, r])
            # 小根堆 min_
            heappush(min_, [num, r])
            # l 为左指针位置
            while -max_[0][0] - min_[0][0] > limit:
                # 条件判断需要max,min[0][0]存的索引不在 l 左侧
                # 删除不在 l 右侧的元素
                while min_[0][1] <= l:
                    heappop(min_)
                while max_[0][1] <= l:
                    heappop(max_)
                # 移动 l
                l += 1
            # 找到最长的符合要求的窗口长度
            if r - l + 1 > res:
                res = r - l + 1
        return res

猜你喜欢

转载自www.cnblogs.com/oldby/p/12823221.html
今日推荐