隊列的最大值(LeetCode 面試題59 - II)

題目

請定義一個隊列并實現(xiàn)函數(shù) max_value 得到隊列里的最大值,要求函數(shù)max_value、push_back 和 pop_front 的時間復(fù)雜度都是O(1)。

若隊列為空,pop_front 和 max_value 需要返回 -1

示例 1:

輸入:
["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
[[],[1],[2],[],[],[]]
輸出: [null,null,null,2,1,2]

示例 2:

輸入:
["MaxQueue","pop_front","max_value"]
[[],[],[]]
輸出: [null,-1,-1]

限制:

1 <= push_back,pop_front,max_value的總操作數(shù) <= 10000
1 <= value <= 10^5

解析

使用一個List維護最大值

  • 判斷maxList是否為空并且當(dāng)前的值是否大于maxList的最后一個值
    • 如果滿足上述條件,直接循環(huán)移除末尾元素
    • 直至條件不滿足時,將當(dāng)前值加入到尾部
  • 取最大值時直接取下標(biāo)為0的位置
  • 彈出元素時,隊列直接彈出,最大值的移除條件(int pop = oriQuene.Dequeue();
    if(pop == maxList[0])
    maxList.RemoveAt(0);)

代碼

public class MaxQueue
    {
        private Queue<int> oriQuene;
        private List<int> maxList;
    
        public MaxQueue() {
            oriQuene = new Queue<int>();
            maxList = new List<int>();
        }
    
        public int Max_value()
        {
            if (maxList.Count == 0) return -1;
            int maxValue = maxList[0];
            return maxValue;
        }
    
          public void Push_back(int value) {
            oriQuene.Enqueue(value);
            while (maxList.Count > 0 && maxList[maxList.Count-1]<value)
            {
                maxList.RemoveAt(maxList.Count-1);
            }
            maxList.Add(value);
        }
    
      public int Pop_front()
        {
            if (oriQuene.Count == 0) return -1;
            int pop = oriQuene.Dequeue();
            if(maxList.Count>0&&pop == maxList[0])
                maxList.RemoveAt(0);
            return pop;
        }
    }

/**
 * Your MaxQueue object will be instantiated and called as such:
 * MaxQueue obj = new MaxQueue();
 * int param_1 = obj.Max_value();
 * obj.Push_back(value);
 * int param_3 = obj.Pop_front();
 */
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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