leetcode刷題筆記-Monotonic queue/Stack

239. Sliding Window Maximum

 https://www.youtube.com/watch?v=2SXqBsTR6a8

class Solution(object):
    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        d = collections.deque()
        out = []
        
        for i, n in enumerate(nums):
            while d and nums[d[-1]] < n:
                d.pop()
                
            d.append(i)
            if d[0] == i - k:  # 存了K+1個元素了
                d.popleft()
            if i >= k - 1:
                out.append(nums[d[0]])
        return out

907. Sum of Subarray Minimums

    public int sumSubarrayMins(int[] A) {
        Stack<Integer> s = new Stack<>();
        int n = A.length, res = 0, mod = (int)1e9 + 7, j,k;
        for (int i = 0; i <= n; i++) {
            while (!s.isEmpty() && A[stack.peek()] > (i == n ? 0 : A[i])) {
                j = stack.pop();
                k = stack.isEmpty() ? -1 : stack.peek();
// i is right boundary   k is left boundary
                res = (res + A[j] * (i - j) * (j - k)) % mod; 
            }
            stack.push(i);
        }
        return res;
    }
class Solution:
    def sumSubarrayMins(self, A):
        res = 0
        stack = []  #  non-decreasing 
        A = [float('-inf')] + A + [float('-inf')]
        for i, n in enumerate(A):
            while stack and A[stack[-1]] > n:
                cur = stack.pop()
                res += A[cur] * (i - cur) * (cur - stack[-1]) 
            stack.append(i)
        return res % (10**9 + 7)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章