2010-04-10 75 views
2

請注意,內存不受限制。 我需要從1插入INT到1000以下情況下的數據結構如何? (最大堆棧)

我可以做以下每個操作都必須在恆定順序的時間

  1. 推():增加了頂部
  2. 流行():刪除棧頂元素
  3. GetMax的():返回最大元素

請建議我適當的數據結構。

+1

聽起來像家庭作業。你自己的努力在哪裏? – 2010-04-10 17:43:31

+0

給我們一個這個getMax應該做什麼的定義 – 2010-04-10 17:44:26

+0

@Coronatus在採訪中這是我問的,我無法回答。所以我正在尋找一個答案 – 2010-04-10 18:19:42

回答

3

由於沒有內存限制,我將使用2個矢量 - 一個用於堆棧上的實際數據,另一個用於跟蹤每個堆棧狀態下的最大值。
爲了簡單起見,我假設這個堆棧只包含+ ve int。
我知道這沒有任何錯誤檢查。但我只是在這裏提供數據結構的想法,而不是完整的解決方案。

class StackWithMax 
{ 
public: 
    StackWithMax() : top(-1), currentMax(0) { } 
    void push(int x); 
    int pop(); 
    int getMax() { return m[top]; } 
private: 
    vector<int> v; // to store the actual elements 
    vector<int> m; // to store the max element at each state 
    int top; 
    int currentMax; 
}; 

void StackWithMax::push(int x) 
{ 
    v[++top] = x; 
    m[top] = max(x, currentMax); 
} 

int StackWithMax::pop() 
{ 
    int x = v[top--]; 
    currentMax = m[top]; 
    return x; 
} 
+0

你還需要在流行音樂中對'm'做些什麼,不是嗎? +1,無論如何。 – 2010-05-28 03:57:39

+0

@Moron:謝謝你指出。我已經改變了'pop()'。 – AngryWhenHungry 2010-05-28 04:07:26

-1

對計數器使用正常堆棧結構和附加陣列 int c[1..1000]和變量int maxVal=0

在代碼的堆棧操作之後添加操作:

On push(x) -> c[x]++ ; maxVal = max(x,maxVal) 
On pop():x -> c[x]-- ; if (c[x] == 0) { j=x; while(c[--j] == 0); maxVal = j; } 

MAXVAL應該始終最大值。或許我錯了,這應該有分期計算複雜度O(1)。 我一直在分析算法已經很長時間了。

+0

這是不正確的。每個上述操作應該按照時間順序完成。 – 2010-04-10 18:17:43