def maxSlidingWindow(nums, k):
    if not nums:
        return []

    h = MaxHeap()

    for i in xrange(k):
        h.add((nums[i], i))

    max_list = [h.peek()[0]]

    for i in xrange(1, len(nums) - k + 1):
        # max is to the left of window
        # remove all previous max items that are no longer in the window,
        # from the heap
        while h and h.peek()[1] < i:
            h.remove()

        # add item at end of current window, i+k-1, to the heap
        h.add((nums[i + k - 1], i + k - 1))

        # add current window's max from the top of the heap
        max_list.append(h.peek()[0])

    return max_list
Esempio n. 2
0
    def test_remove(self):
        l = [5, 4, 3, 2, 1, 6, 7, 8, 9, 0]
        h = MaxHeap()

        caught_exception = False
        try:
            assert h.peek() == None
        except HeapEmptyError as e:
            assert str(e) == "HeapEmptyError: 'peek(): Heap is empty'"
            caught_exception = True
        assert caught_exception == True

        caught_exception = False
        try:
            assert h.remove() == None
        except HeapEmptyError as e:
            assert str(e) == "HeapEmptyError: 'remove(): Heap is empty'"
            caught_exception = True
        assert caught_exception == True

        for i in xrange(len(l)):
            h.add(l[i])

        assert len(h) == 10
        for i in xrange(9, -1, -1):
            item = h.remove()
            assert (len(h) == i)
            assert item == i