高頻算法面試題 3.隊(duì)列(Queue)

  • 定義:
    特殊的線性表,只能在前端刪除,后端插入,先進(jìn)先出(FIFO—first in first out)線性表。類比排隊(duì)一樣,先排進(jìn)隊(duì)列的人先出去。
  • 代碼實(shí)現(xiàn):
#FIFO: first item we insert will be the first we take out
class Queue:

    #we represent the queue with the help of an array
    def __init__(self):
        self.queue = []
        
    #checks if the queue is empty or not    
    def is_empty(self):
        return self.queue == []
        
    #inserting items 
    def enqueue(self, data):
        self.queue.append(data)
        
    #getting items
    def dequeue(self):
    
        #maybe there is no item in the queue
        if self.is_empty():
            raise Exception("Queue is empty...")
    
        #getting the first item
        data = self.queue[0]
        del self.queue[0]
        return data
        
    #getting the item without removing it
    def peek(self):
        
        #maybe there is no item in the queue
        if self.is_empty():
            raise Exception("Queue is empty...")
    
        return self.queue[0]
    
    #size of the queue
    def size_queue(self):
        return len(self.queue)
    
if __name__ == "__main__":      
    
    queue = Queue()
    
    queue.enqueue(10)
    queue.enqueue(20)
    queue.enqueue(30)
    
    print(queue.size_queue())
    print("Dequeue: ", queue.dequeue())
    print("Dequeue: ", queue.dequeue())
    print(queue.size_queue())


題目

225和239


leetcode 239

思路
暴力解法: 遍歷所有區(qū)間,[0,len(nums)-k)], 遍歷[x,x+k]窗口得到最大值.
為什么優(yōu)化解法用到max-heap(堆)呢? 因?yàn)榇翱诿看蜗蛴一瑒?dòng)都是減去一個(gè)值 加上一個(gè)最大值,符合堆的特性.


暴力和O(nlogn)解法

https://realpython.com/modern-web-automation-with-python-and-selenium/

O(n)解法
觀察數(shù)組中數(shù)的性質(zhì):
如果窗口中有a,b兩數(shù),a在b之前,且a <= b, 那么a不可能為最大值。
如圖,注意到窗口中的數(shù)是單調(diào)遞減的


原來(lái)的數(shù)組
image
按照性質(zhì)去掉符合的數(shù)之后

算法


O(n)解法

實(shí)現(xiàn)
*雙端隊(duì)列:雙端隊(duì)列是指允許兩端都可以進(jìn)行入隊(duì)和出隊(duì)操作的隊(duì)列


image.png
class Solution(object):
    
    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        from collections import deque
        #定義插入一個(gè)數(shù)的操作,輸入是(時(shí)間戳,數(shù)字)
        def add(i,num):
            #判斷隊(duì)首是否應(yīng)該出隊(duì)
            if len(q) != 0 and q[0][0] == i-k:
                q.popleft()
            #判斷隊(duì)尾是否應(yīng)該出隊(duì)
            while (len(q) != 0 and num >= q[-1][1]):
                q.pop()
            #插入新二元組
            q.append((i,num))
            
            #返回隊(duì)首,即當(dāng)前最大值
            return q[0][1]
        q = deque()
        
        res = []
        for i,num in enumerate(nums):
            res.append(add(i,num))
        
        #結(jié)果只保留k-1往后的,前面的結(jié)果都不到k個(gè)數(shù)
        return res[k-1:]

leetcode相關(guān)

  1. #225 Implement Stack using Queues
  2. #232 Implement Queue using Stacks
  3. #239 Sliding Window Maximum
  4. #621 Task Scheduler
  5. #622 Design Circular Queue
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒(méi)有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,679評(píng)論 1 32
  • 1.設(shè)計(jì)模式是什么? 你知道哪些設(shè)計(jì)模式,并簡(jiǎn)要敘述?設(shè)計(jì)模式是一種編碼經(jīng)驗(yàn),就是用比較成熟的邏輯去處理某一種類型...
    龍飝閱讀 2,305評(píng)論 0 12
  • 很容易滿足 一粥兩飯三餐四季 空氣里都彌漫著知足常樂(lè)的味道 對(duì)于一個(gè)吃貨來(lái)說(shuō) 你多么英俊瀟灑 英明神武 都比不過(guò)一...
    未曉啊閱讀 326評(píng)論 0 3
  • 敬畏一切,回歸簡(jiǎn)單 這一場(chǎng)胃病折磨我了這快一個(gè)十一長(zhǎng)假,從最初...
    拙蘭閱讀 460評(píng)論 11 14

友情鏈接更多精彩內(nèi)容