题意:实现一个新定义的stack(栈)数据结果,除了能实现栈的正常功能外,还需增加返回栈内最小元素值的功能,并且要求时间复杂度是常量级。
总结:自己看题没有理解清楚,以为只是简单的构造一个常规stack,忽略了对时间复杂度的要求,而这个正式本题的考点,要求返回栈内元素最小值所需要的时间复杂度是常数级(说明不能用遍历的方法),所以前两种方法(vector和链表方法都是通过遍历的方式求得最小元素的值,时间复杂度都很高o(n));第三种方法是网友的方法,实质就是在创建stack的同时还要考虑min元素的信息,可以用两个stack数据结构,也可以stack
#include
#include
#include
using namespace std;
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
//方法一:先用vector方法做一下,时间效率很低
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
stack.push_back(x);
}
void pop() {
stack.pop_back();
}
int top() {
return stack.back();
}
int getMin() {
int min = stack.front();
vector
for (it = stack.begin(); it != stack.end(); ++it)
{
if ((*it) < min) min = (*it);
}
return min;
}
private:
vector
};
//方法二:通过双向链表实现一个stack类的数据结构
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
head = nullptr;
last = nullptr;
}
void push(int x) {
Nodelist ptr = (Nodelist)malloc(sizeof(Node));
ptr->val = x;
ptr->next = nullptr;
ptr->front = nullptr;
if (!head)
{
head = ptr;
last = head;
}
else
{
last->next = ptr;
ptr->front = last;
last = ptr;
}
}
void pop() {
if (head) {
if (last != head)
{
Nodelist temp = last;
last = last->front;
last->next = nullptr;
free(temp);
temp = nullptr;
}
else
{
free(head);
head = nullptr;
last = nullptr;
}
}
else
cout << "Wrong operations!" << endl;
}
int top() {
return last->val;
}
int getMin() {
if (!head) cout << "Wrong operations!" << endl;
Nodelist temp = head;
int min = head->val;
while (temp) {
if (temp->val < min) min = temp->val;
temp = temp->next;
};
return min;
}
private:
typedef struct Node {
int val;
struct Node* next;
struct Node* front;
}Node, * Nodelist;
Nodelist head, last;
};
//方法三:网友方法,非常精简犀利
class MinStack {
public:
/** initialize your data structure here. */
stack< pair
MinStack() {
}
void push(int x) {
//这两种条件判断的太好了
if (s.empty() || s.top().second >= x)
s.push({ x, x });
else
s.push({ x, s.top().second });
}
void pop() {
s.pop();
}
int top() {
return s.top().first;
}
int getMin() {
return s.top().second;
}
};