2010-04-10 70 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