Leetcode [tag Sliding Window] 3, 239.

经典 滑动窗口+hashset
3. Longest Substring Without Repeating Characters
最长无重复子串,经典

    def lengthOfLongestSubstring(self, s: str) -> int:
        if s == "":
            return 0
        d = {}
        res = 1
        start = 0
        for i in range(len(s)):
            if s[i] in d:
                start = max(start,d[s[i]] + 1)
            d[s[i]] = i
            res = max(res, i - start + 1)
        return res

239. Sliding Window Maximum(hard)

这道题剑指offer上也有,比较巧妙,暴力方法需要O(n*k),而双向队列缩短到了O(n)

    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        queue = []
        i, res = 0, []
        while i < len(nums):
            if len(queue) > 0 and i - k + 1 > queue[0]: #超过k弹出
                queue.pop(0)
            while len(queue) > 0 and nums[queue[-1]] < nums[i]: #大数替换小数
                queue.pop()
            queue.append(i)  #加入队列的是数组的位置
            if i >= k -1:  #开始时添加queue数
                res.append(nums[queue[0]])
            i += 1
        return res

你可能感兴趣的:(Leetcode [tag Sliding Window] 3, 239.)