队列的最大值

2018-05-13  本文已影响0人  vckah
# coding:utf-8
# 借助 collections 里的 deque
from collections import deque
def maxSlideWindow(nums, k):
    if k == 1:
        return nums
    qmax = deque([])
    qmax.append(0)
    res = []

    for x, y in enumerate(nums[1:], 1):
        if nums[qmax[-1]] <= y:
        # 如果数组中当前值大于队列中最后一个值,那么队列中最后一个值不可能成为当前窗口最大值
            for i in range(len(qmax)-1, -1, -1):
                if nums[qmax[i]] > y:
                    break
                else:
                    qmax.pop()
        # 如果数组中当前值小于队列中的值,那么其有可能成为窗口的最大值,将其存入队列
        qmax.append(x)
        #当qmax存在过期数据,即不在移动k范围内的,将其移除出双端队列
        if qmax[0] <= x-k:
            qmax.popleft()
        # 将每次移动窗口的最大值存储到res中
        if x >= k-1:
            res.append(nums[qmax[0]])
    return res

a = [1,2,7,7,8]
print maxSlideWindow(a, 3)
def minSubArrayLen(s, nums):
    """
    :type s: int
    :type nums: List[int]
    :rtype: int
    """
    if not nums:
        return 0
    r = 0
    summ = 0
    minn = None
    l = 0

    while r < len(nums):
        summ += nums[r]
        r += 1
        
        while summ >= s:
            cand = r - l
            summ -= nums[l]
            l += 1
            if minn is None:
                minn = cand
            else:
                minn = min(minn, cand)
    
    if minn is None:
        return 0
    return minn

a = [2, 3, 1, 2, 4, 3]
s = 5
print(minSubArrayLen(s, a))
def lengthOfLongestSubstring(s):
        """
        :type s: str
        :rtype: int
        """
        used = {}
        max_length = start = 0
        for i, c in enumerate(s):
            if c in used and start <= used[c]:
                start = used[c] + 1
            else:
                max_length = max(max_length, i - start + 1)
            used[c] = i
        return max_length

s = 'abcdabcabcd'
print(lengthOfLongestSubstring(s))
上一篇 下一篇

猜你喜欢

热点阅读