1. 程式人生 > >3.20 包含min函式的棧

3.20 包含min函式的棧

定義棧的資料結構,請在該型別中實現一個能夠得到棧中所含最小元素的min函式(時間複雜度應為O(1))。

class Solution {
public:
	void push(int value) {
		stack.push(value);
		map[value] += 1;
	}
	void pop() {
		int val = stack.top();
		stack.pop();
		map[val] -= 1;
		if (map[val] <= 0) {
			map.erase(val);
		}
	}
	int top() {
		return stack.top();
	}
	int min() {
		if (!map.empty()) {
			return map.begin()->first;
		}
		return -1;
	}

	std::stack<int> stack;
	std::map<int,int> map;
};
測試

在這裡插入圖片描述