LintCode 360 [Sliding Window Median]

原題

給定一個(gè)包含 n 個(gè)整數(shù)的數(shù)組,和一個(gè)大小為 k 的滑動(dòng)窗口,從左到右在數(shù)組中滑動(dòng)這個(gè)窗口,找到數(shù)組中每個(gè)窗口內(nèi)的最大值。(如果數(shù)組中有偶數(shù),則在該窗口存儲(chǔ)該數(shù)字后,返回第 N/2-th 個(gè)數(shù)字。)

對(duì)于數(shù)組 [1,2,7,8,5], 滑動(dòng)大小 k = 3 的窗口時(shí),返回 [2,7,7]
最初,窗口的數(shù)組是這樣的:
[ 1,2,7 ,8,5] , 返回中位數(shù) 2;
接著,窗口繼續(xù)向前滑動(dòng)一次。
[1, 2,7,8 ,5], 返回中位數(shù) 7;
接著,窗口繼續(xù)向前滑動(dòng)一次。
[1,2, 7,8,5 ], 返回中位數(shù) 7;

解題思路

  • 類似題是[Data Stream Median],[Data Stream Median]維護(hù)了一個(gè)max heap和一個(gè)min heap,不需要?jiǎng)h除操作
  • 本題是滑動(dòng)窗口類型題目,分為兩個(gè)操作,加入新元素,刪除頭部元素
  • 由于涉及刪除元素,所以要維護(hù)一個(gè)hash max heap和一個(gè)hash min heap

完整代碼

class node:
    """
    create a node class to handle the duplicates in heap.
    id => the index of x, num = number of x in heap
    """
    def __init__(self, id, number):
        self.id = id
        self.num = number

class HashHeap:
    def __init__(self):
        self.map = {}
        self.hashmaxheap = [0]
        self.map[0] = node(0, 1)
        self.currentSize = 0

    def put(self, data):
        """add a new item to the hashmaxheap"""
        if data in self.map:
            existData = self.map[data]
            self.map[data] = node(existData.id, existData.num + 1)
            self.currentSize += 1
            return 
        else:
            self.hashmaxheap.append(data)
            self.map[data] = node(len(self.hashmaxheap) - 1, 1)
            self.currentSize += 1
            self.siftUp(len(self.hashmaxheap) - 1)

    def peek(self):
        """returns the item with the maxmum key value"""
        return self.hashmaxheap[1]

    def get(self):
        """returns the item with the maxmum key value, removing the item from the heap"""
        res = self.hashmaxheap[1]
        if self.map[res].num == 1:
            if self.map[res].id == len(self.hashmaxheap) - 1:
                del self.map[res]
                self.hashmaxheap.pop()
                self.currentSize -= 1
                return res
            del self.map[res]
            self.hashmaxheap[1] = self.hashmaxheap[-1]
            self.map[self.hashmaxheap[1]] = node(1, self.map[self.hashmaxheap[1]].num)
            self.hashmaxheap.pop()
            self.siftDown(1)
        else:
            self.map[res] = node(1, self.map[res].num - 1)
        self.currentSize -= 1
        return res

    def delete(self, data):
        existData = self.map[data]
        if existData.num == 1:
            del self.map[data]
            if existData.id == len(self.hashmaxheap) - 1:
                self.hashmaxheap.pop()
                self.currentSize -= 1
                return
            self.hashmaxheap[existData.id] = self.hashmaxheap[-1]
            self.map[self.hashmaxheap[-1]] = node(existData.id, self.map[self.hashmaxheap[-1]].num)
            self.hashmaxheap.pop()
            self.siftUp(existData.id)
            self.siftDown(existData.id)
        else:
            self.map[data] = node(existData.id, existData.num - 1)
        self.currentSize -= 1

    def siftUp(self, index):
        # // means devide by 2 and return int
        while index // 2 > 0:
            if self.hashmaxheap[index] < self.hashmaxheap[index // 2]:
                break
            else:
                numA = self.map[self.hashmaxheap[index]].num
                numB = self.map[self.hashmaxheap[index // 2]].num
                self.map[self.hashmaxheap[index]] = node(index // 2, numA)
                self.map[self.hashmaxheap[index // 2]] = node(index, numB)
                self.hashmaxheap[index], self.hashmaxheap[index // 2] = self.hashmaxheap[index // 2], self.hashmaxheap[index] 
            index = index // 2

    def siftDown(self, index):
        """correct single violation in a sub-tree"""
        if index > (len(self.hashmaxheap) - 1) // 2:
            return
        # find the max child of current index
        if (index * 2 + 1) > (len(self.hashmaxheap) - 1) or self.hashmaxheap[index * 2] > self.hashmaxheap[index * 2 + 1]:
            maxChild = index * 2
        else:
            maxChild = index * 2 + 1
        if self.hashmaxheap[index] > self.hashmaxheap[maxChild]:
            return
        else:
            numA = self.map[self.hashmaxheap[index]].num
            numB = self.map[self.hashmaxheap[maxChild]].num
            self.map[self.hashmaxheap[index]] = node(maxChild, numA)
            self.map[self.hashmaxheap[maxChild]] = node(index, numB)
            self.hashmaxheap[index], self.hashmaxheap[maxChild] = self.hashmaxheap[maxChild], self.hashmaxheap[index] 
        self.siftDown(index * 2)
        self.siftDown(index * 2 + 1)

    def size(self):
        return self.currentSize

    def isEmpty(self):
        return self.currentSize == 0
        
class Solution:
    """
    @param nums: A list of integers.
    @return: The median of element inside the window at each moving.
    """
    def medianSlidingWindow(self, nums, k):
        res = []
        if not nums:
            return res
            
        median = nums[0]
        minHeap = HashHeap()
        maxHeap = HashHeap()
        for i in range(len(nums)):
            if i != 0:
                if nums[i] > median:
                    minHeap.put(- nums[i])
                else:
                    maxHeap.put(nums[i])
            if i >= k:
                if median == nums[i - k]:
                    if not maxHeap.isEmpty():
                        median = maxHeap.get()
                    elif not minHeap.isEmpty():
                        median = - minHeap.get()
                elif median < nums[i - k]:
                    minHeap.delete(- nums[i - k])
                else:
                    maxHeap.delete(nums[i - k])
                    
            while maxHeap.size() > minHeap.size():
                minHeap.put(- median)
                median = maxHeap.get()
            
            while minHeap.size() > maxHeap.size() + 1:
                maxHeap.put(median)
                median = - minHeap.get()
                
            if i + 1 >= k:
                res.append(median)
                
        return res
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,769評(píng)論 0 33
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,923評(píng)論 18 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,284評(píng)論 25 708
  • 新春,新氣象,新征程,新收獲。為幫助學(xué)生迅速消除“寒假綜合癥”,以嶄新的姿態(tài),飽滿的精神,滿腔的熱情投入到新的學(xué)...
    li俊青閱讀 493評(píng)論 0 1
  • 《中國(guó)式眾籌》閱讀進(jìn)入第三章,案例部分,今天的10頁(yè)講了金融客咖啡的案例。 關(guān)于金融,我一沒(méi)經(jīng)驗(yàn)二沒(méi)興趣,所以此案...
    珞珈紫陌閱讀 117評(píng)論 0 0