【问题标题】:What is the fastest way to search the maximum element in a stack in Java?在Java中搜索堆栈中最大元素的最快方法是什么?
【发布时间】:2017-07-13 06:09:12
【问题描述】:

我有一个问题,我必须在堆栈中搜索最大元素。我创建了自己的堆栈类并使用了以下方法:

   Node node = top; //created a new node which points to the top of stack

   int max = node.data;  //max contains the value of the top node

   while(node != null) {
           if(node.data > max) {
              max = node.data;
           }
           node = node.next;
    }

   //Print the value of max.

谁能提出一个更有效的方法来做到这一点?

【问题讨论】:

  • 除非您的堆栈以某种方式排序,否则没有比 O(n) 更快的方法!?您可以使用多线程解决方案,但可能就是这样。

标签: java search data-structures stack


【解决方案1】:

维护两个堆栈:

  1. 由所有节点组成。
  2. 始终将 Max 节点保持在其顶部,这样每次都可以更轻松地获取最大元素。

代码如下:

import java.util.Stack;

public class StackWithMax extends Stack<Integer> {

Stack<Integer> s2;

public StackWithMax() {
    s2 = new Stack<Integer>();      
}

public void push(int value){
    if (value >= max()) {
        s2.push(value);
    }
    super.push(value);
}

public Integer pop() {
    int value = super.pop();
    if (value == max()) {
        s2.pop();           
    }
    return value;
}

public int max() {
    if (s2.isEmpty()) {
        return Integer.MIN_VALUE;
    } else {
        return s2.peek();
    }
  }
} 

【讨论】:

  • 如果你这样做,为什么不简单地在堆栈类中保存一个int max而不是另一个堆栈!?
  • @Xander 如果你只保存一个max,那么当你弹出一个元素时,你必须遍历整个堆栈才能再次找出max
  • @Xander 我们必须遍历整个堆栈才能再次找到最大值。
  • @xander 当一个元素从堆栈中移除并且它是最大值时,您需要遍历整个堆栈以找到之前的第二大值,即新的最大值...跨度>
  • 您没有正确覆盖 push 方法的事实使得这很容易出错。
【解决方案2】:

如果您可以使用额外的空间,我们可以在 O(1) 时间内执行 getMax()。这个想法是使用基于返回两个元素最大值的比较器的 PriorityQueue。您的 PriorityQueue 将由基于您的比较器以排序方式排列的元素组成。每当您在堆栈中推送一个元素时,您也会在 PriorityQueue 中推送与该元素对应的最大元素。举个例子:

假设在您的堆栈中您正在推送元素 3。那么在您的priorityQueue pQ 中,您将提供 3。此时,3 将是堆栈中对应于 3 的最大元素。

让我们在堆栈 S 中插入 5。在 pQ 中提供 5。由于 5 > 3,pQ 中元素的顺序将为 5 3。 让我们在 S 中推 4。在 pQ 中也提供 4。 pQ 现在将包含元素:5 4 3. 如果你执行 getMax(),你会得到 pQ 的头部,这需要 O(1) 时间,因为最大元素总是在 pQ 的顶部。

在 S.pop() 的情况下,如果您将 pQ 以 LinkedList 的形式存储,您也可以在 O(1) 时间内从 pQ 中删除相应的弹出元素。因此,所有这些操作都需要 O(1) 时间。

按照同样的逻辑,你也可以在 O(1) 时间内执行 popMax()。只需返回 pQ 的头部并从 Stack 中删除相应的节点,这同样可以在 O(1) 时间内完成。

以下是两者的结构:

public class Node{
    int data;
    Node next;
    Node(int data){
        this.data = data;
        next = null;
    }
}

PriorityQueue<Node> pQ = new PriorityQueue<Node>();
Stack<Node> S = new Stack<Node>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2014-08-27
    • 2013-08-22
    • 2021-09-07
    • 2011-01-24
    相关资源
    最近更新 更多