Peek()如何工作?
import java.util.Scanner;
import java.util.Stack;
// All 3 queries (1:push, 2:delete, 3:print max) are all O(1) runtime
public class Solution {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> maxStack = new Stack<Integer>(); // keeps track of maximums
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
for (int i = 0; i < N; i++) {
int query = scan.nextInt();
switch (query) {
case 1:
int x = scan.nextInt();
stack.push(x);
if (maxStack.isEmpty() || x >= maxStack.peek()) {
maxStack.push(x);
}
break;
case 2:
int poppedValue = stack.pop();
if (poppedValue == maxStack.peek()) {
maxStack.pop();
}
break;
case 3:
System.out.println(maxStack.peek());
break;
default:
break;
}
}
scan.close();
}
}
这是在堆栈中查找最大值的代码,我想知道,如果peek()
选择堆栈的顶部元素,那么如果有一个元素大于最高值,则该元素的窥视方式堆栈。如何确定最大值
import java.util.Scanner;
import java.util.Stack;
// All 3 queries (1:push, 2:delete, 3:print max) are all O(1) runtime
public class Solution {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> maxStack = new Stack<Integer>(); // keeps track of maximums
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
for (int i = 0; i < N; i++) {
int query = scan.nextInt();
switch (query) {
case 1:
int x = scan.nextInt();
stack.push(x);
if (maxStack.isEmpty() || x >= maxStack.peek()) {
maxStack.push(x);
}
break;
case 2:
int poppedValue = stack.pop();
if (poppedValue == maxStack.peek()) {
maxStack.pop();
}
break;
case 3:
System.out.println(maxStack.peek());
break;
default:
break;
}
}
scan.close();
}
}
This is code for finding max value in the stack i want to know that if peek()
chooses the top element of the stack than how it will peek if there is an element greater than top value like in between the stack. how it will determine the max value
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用您的情况(最多之间),它可以正常工作:
如果您在
stack
中具有值:1,4,5,3,2,1
- 然后。并执行案例2:
将留下stack
带有1,2,5,3,2
和MaxStack
不会被弹出,所以仍然有5个作为顶级元素。但是,使用
的顺序1,2,3,5,5
删除查询将从stack
和maxstack
中执行POP(),它导致:stack
- &gt; 1,2,3,5maxstack
- &gt; 1,2,3我认为这是逻辑中的缺陷。
With you case (max in between) it works fine:
If you have values in the
stack
:1,4,5,3,2,1
- thenmaxStack
will contain 5 as the top element. And executingcase 2:
will leavestack
with1,2,5,3,2
andmaxStack
will not be popped so still have 5 as top element.However with the sequence of
1,2,3,5,5
delete query will execute pop() from bothstack
andmaxStack
which leads to:stack
-> 1,2,3,5maxStack
-> 1,2,3Which I believe is a flaw in the logic.