publicintlargestRectangleArea(int[] heights) {if (heights.length==0) {return0; }Stack<Integer> stack =newStack<>();int max =0;// 当前高度小于栈,则将栈内元素都弹出计算面积for (int i =0; i <=heights.length; i++) {int cur =0;if (i <heights.length) { cur = heights[i]; }while (stack.size() !=0&& cur <= heights[stack.peek()]) {int index =stack.pop();int h = heights[index];// 计算宽度int w = i;if (stack.size() !=0) {int peek =stack.peek(); w = i - peek -1; } max =Math.max(max, h * w); }// 记录索引即可获取对应元素stack.push(i); }return max;}
classMyQueue {privateStack<Integer> stack1 =newStack<>();privateStack<Integer> stack2 =newStack<>(); /** Initialize your data structure here. */publicMyQueue() { } /** Push element x to the back of queue. */publicvoidpush(int x) {while (!stack2.isEmpty()) {int val =stack2.pop();stack1.push(val); }stack1.push(x); } /** Removes the element from in front of queue and returns that element. */publicintpop() {while (!stack1.isEmpty()) {int val =stack1.pop();stack2.push(val); }if (stack2.isEmpty()) return-1;returnstack2.pop(); } /** Get the front element. */publicintpeek() {while (!stack1.isEmpty()) {int val =stack1.pop();stack2.push(val); }if (stack2.isEmpty()) return-1;returnstack2.peek(); } /** Returns whether the queue is empty. */publicbooleanempty() {returnstack1.isEmpty() &&stack2.isEmpty(); }}