面試題59_2:隊(duì)列的最大值

定義一個(gè)隊(duì)列,實(shí)現(xiàn)max方法得到隊(duì)列中的最大值。

  • 要求入列、出列以及邱最大值的方法時(shí)間復(fù)雜度都是O(1)

private Deque<Integer> dataQueue = new LinkedList<>();
private Deque<Integer> maxQueue = new LinkedList<>();

    /**
     * 另外加一個(gè)保存最大值的隊(duì)列
     * @param number
     */
    public void offer(int number) {
        dataQueue.offer(number);
        // 即將要存入的元素比當(dāng)前隊(duì)列最大值還大,存入該元素
        // 即將要存入的元素不超過(guò)當(dāng)前隊(duì)列最大值,再將最大值存入一次
        if (maxQueue.isEmpty() || number > maxQueue.peekFirst()) maxQueue.offerFirst(number);
        else maxQueue.offerFirst(maxQueue.peekFirst());

    }

    public void poll() {
        //!!!取隊(duì)列和棧時(shí),一定要最空值判斷
       if (dataQueue.isEmpty()) throw new RuntimeException("隊(duì)列為空!");
       if (maxQueue.peekFirst() == dataQueue.peekFirst()){
           maxQueue.pollFirst();
       }
       dataQueue.pollFirst();

    }

    public int max() {
        //空值判斷?。?!
       if (maxQueue.isEmpty()) throw new RuntimeException("隊(duì)列為空!");
       return maxQueue.peekFirst();
    }
    public static void main(String[] args) {
        MaxQueue maxQueue = new MaxQueue();
        maxQueue.offer(2);
        maxQueue.offer(3);
        maxQueue.offer(4);
        maxQueue.offer(2);
        maxQueue.offer(6);
        maxQueue.offer(2);
        maxQueue.offer(5);
        maxQueue.offer(1);

        System.out.println(maxQueue.max());
        maxQueue.poll();
        maxQueue.poll();
        maxQueue.poll();
        maxQueue.poll();
        System.out.println(maxQueue.max());
        maxQueue.poll();
        System.out.println(maxQueue.max());
        maxQueue.poll();
        System.out.println(maxQueue.max());

    }
?著作權(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)容

  • 一、基本數(shù)據(jù)類型 注釋 單行注釋:// 區(qū)域注釋:/* */ 文檔注釋:/** */ 數(shù)值 對(duì)于byte類型而言...
    龍貓小爺閱讀 4,455評(píng)論 0 16
  • 本系列出于AWeiLoveAndroid的分享,在此感謝,再結(jié)合自身經(jīng)驗(yàn)查漏補(bǔ)缺,完善答案。以成系統(tǒng)。 Java基...
    濟(jì)公大將閱讀 1,617評(píng)論 1 6
  • 目錄 1. 棧和隊(duì)列1.用兩個(gè)隊(duì)列實(shí)現(xiàn)棧2.用兩個(gè)棧實(shí)現(xiàn)隊(duì)列3.實(shí)現(xiàn)一個(gè)棧,可以用常數(shù)級(jí)時(shí)間找出棧中的最小值4.判...
    MigrationUK閱讀 3,131評(píng)論 4 20
  • 面向?qū)ο笾饕槍?duì)面向過(guò)程。 面向過(guò)程的基本單元是函數(shù)。 什么是對(duì)象:EVERYTHING IS OBJECT(萬(wàn)物...
    sinpi閱讀 1,220評(píng)論 0 4
  • 原創(chuàng)作者/山水平生 熟悉我的人都知道,在讀初中前我沒(méi)有出過(guò)山,跟原始部落里的小角色一樣,成天就是上小學(xué),放羊,做家...
    山水平生閱讀 753評(píng)論 8 6

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