LeetCode-Algorithms-[Easy]面试题30. 包含min函数的栈

面试题30. 包含min函数的栈

	class MinStack {
		Stack<Integer> s1;
		Stack<Integer> s2;

		/** initialize your data structure here. */
		public MinStack() {
			this.s1 = new Stack<Integer>();
			this.s2 = new Stack<Integer>();
		}

		public void push(int x) {
			s1.add(x);
			if (s2.isEmpty() || x <= s2.peek()) {
				s2.add(x);
			}
		}

		public void pop() {
			int res = s1.pop();
			if (s2.peek().equals(res)) {
				s2.pop();
			}
		}

		public int top() {
			return s1.peek();
		}

		public int min() {
			return s2.peek();
		}
	}
发布了272 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/m0_37302219/article/details/105573209