劍指offer之隊列中的最大值(C++/Java雙重實現)

1.題目描述

請定義一個隊列並實現函數 max_value 得到隊列裏的最大值,要求函數max_value、push_back 和 pop_front 的均攤時間複雜度都是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的總操作數 <= 10000
1 <= value <= 10^5

在這裏插入圖片描述

2.問題分析

只要知道隊列的底層和隊列的特點就很簡單
隊列的底層:數組實現
棧的特點:先進先出,頭刪尾插

3.代碼實現

3.1C++代碼
class MaxQueue {
public:
    int arr[100000];
    int cnt;
    MaxQueue() {

    }
    int max_value() {
        if(cnt==0)
        return -1;
        int max=arr[0];
        for(int i=0;i<cnt;i++)
        {
            if(arr[i]>max)
            max=arr[i];
        }
        return max;

    }
    
    void push_back(int value) {
     arr[cnt++]=value;
    }
    
    int pop_front() {
        if(cnt==0)
        return -1;
        int flag=arr[0];
        for(int i=0;i<cnt-1;i++)
      {
          arr[i]=arr[i+1];
      }
      arr[--cnt]=0;
          return flag;

    }
};

/**
 * 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();
 */
3.2Java代碼
class MaxQueue {
    private int arr[];
    private int cnt;
    public MaxQueue() {
        arr=new int[100000];

    }
    
    public int max_value() {
           if(cnt==0)
        return -1;
        int max=arr[0];
        for(int i=0;i<cnt;i++)
        {
            if(arr[i]>max)
            max=arr[i];
        }
        return max;

    }
    
    public void push_back(int value) {
         arr[cnt++]=value;

    }
    
    public int pop_front() {
        if(cnt==0)
        return -1;
        int flag=arr[0];
        for(int i=0;i<cnt-1;i++)
      {
          arr[i]=arr[i+1];
      }
      arr[--cnt]=0;
          return flag;

    }
}

/**
 * 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();
 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章