leetcode 155 Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
• push(x) – Push element x onto stack.
• pop() – Removes the element on top of the stack.
• top() – Get the top element.
• getMin() – Retrieve the minimum element in the stack.

解决方案:


可以看到STL的解决方案跟大多数的c语言解决方案还是有差距的,后序我找一找基于链表的整齐点的c语言实现

The key idea is use a another stack to store the minimum value of the corresponding stack. Put differently, min[i] equals the minimum element where data[i] is the top of this sub-stack.

We can use a full size of min where it’s size equals the data’s, but it’s not necessary.

I have 2 main concerns about the algorithm:

1
We should pop the element in min IFF there’s match of data.top().

2
If we have multiple minima, for example [0, 1, 0] in data, then the min should be [0, 0].
Otherwise, the the pop operation wouldn’t work properly.
As a result, we should push the element if x <= min.top().

class MinStack {
public:
    void push(int x) {
        s.push(x);
        if (mins.empty() || x<=mins.top()) {
            mins.push(x);
        }
    }

    void pop() {
        int temp = s.top();
        s.pop();
        if (temp == mins.top()) {
            mins.pop();
        }
    }

    int top() {
        return s.top();
    }

    int getMin() {
        return mins.top();
    }

private:
    stack<int> s;
    stack<int> mins;
};

STL list实现:

class MinStack {
    private:
        list<int> s;
        int min;

    public:

        MinStack()
        {
            min=INT_MAX;
        }

        void push(int x) {
            if(x<min) min=x;
            s.push_back(x);

        }

        void pop() {
            if(s.back()==min)
            {
                s.pop_back();
                min=INT_MAX;
                list<int>::iterator it=s.begin();
                while(it!=s.end())
                {
                    if(*it<min) min=*it;
                    it++;
                }
            }else
                s.pop_back();
        }

        int top() {
            return s.back();
        }

        int getMin() {
            return min;
        }
    };

python解决方案:

class MinStack:
# @param x, an integer
def __init__(self):
    # the stack it self
    self.A = []
    self.minS=[]
# @return an integer
def push(self, x):
    n=len(self.A)
    if n==0:
        self.minS.append(x)
    else:
        lastmin=self.minS[-1]
        if x<=lastmin:
            self.minS.append(x)
    self.A.append(x)
# @return nothing
def pop(self):
    if len(self.A)>0 and self.A.pop()==self.minS[-1]:
        self.minS.pop()
# @return an integer
def top(self):
    return self.A[-1]

# @return an integer
def getMin(self):
    return self.minS[-1]

python解决方案2:


class MinStack:

def __init__(self):
    self.q = []

# @param x, an integer
# @return an integer
def push(self, x):
    curMin = self.getMin()
    if curMin == None or x < curMin:
        curMin = x
    self.q.append((x, curMin));

# @return nothing
def pop(self):
    self.q.pop()

# @return an integer
def top(self):
    if len(self.q) == 0:
        return None
    else:
        return self.q[len(self.q) - 1][0]

# @return an integer
def getMin(self):
    if len(self.q) == 0:
        return None
    else:
        return self.q[len(self.q) - 1][1]

  asked Apr 14  in Min Stack  by  charles8135 (180 points)
时间: 2024-10-29 19:30:50

leetcode 155 Min Stack的相关文章

[LeetCode] Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) – Push element x onto stack. pop() – Removes the element on top of the stack. top() – Get the top element. getMin() – Retrieve the minimum eleme

LeetCode: Min Stack 最小栈 Java

题目描述: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the min

Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum e

java中equals和==的区别

[LeetCode]–155. Min Stack 在这个问题中,我遇到了==和equals的问题,虽然试一下就能得出结果,但是我想弄明白. java中的数据类型,可分为两类: 1.基本数据类型,也称原始数据类型.byte,short,char,int,long,float,double,boolean 他们之间的比较,应用双等号(==),比较的是他们的值. 2.复合数据类型(类) 当他们用(==)进行比较的时候,比较的是他们在内存中的存放地址,所以,除非是同一个new出来的对象,他们的比较后的

LeetCode All in One 题目讲解汇总(持续更新中...)

终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通过OJ,或是有更好的解法,或是有任何疑问,意见和建议的话,请一定要在对应的帖子下面评论区留言告知博主啊,多谢多谢,祝大家刷得愉快,刷得精彩,刷出美好未来- 博主制作了一款iOS的应用"Leetcode Meet Me",里面有Leetcode上所有的题目,并且贴上了博主的解法,随时随地都能

UVa 10700:Camel trading

链接: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_problem&problem=1641 原题: Background Aroud 800 A.D., El Mamum, Calif of Baghdad was presented the formula 1+2*3*4+5, which had its origin in the

几个面试经典算法题Java解答

题目一: public class testClockwiseOutput {      //顺时针打印一个矩阵           @Test      public void test(){          int[][] num = new int[100][100];          int n = 4;          int count =1;                   for(int i=0;i<n;i++){              for(int j =0;j

[LeetCode]42.Trapping Rain Water

[题目] Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. For example,  Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. The above elevation map is represente

PostgreSQL 流式统计 - insert on conflict 实现 流式 UV(distinct), min, max, avg, sum, count ...

标签 PostgreSQL , 流式统计 , insert on conflict , count , avg , min , max , sum 背景 流式统计count, avg, min, max, sum等是一个比较有意思的场景,可用于实时大屏,实时绘制统计图表. 比如菜鸟.淘宝.阿里游戏.以及其他业务系统的FEED日志,按各个维度实时统计输出结果.(实时FEED统计,实时各维度在线人数等) PostgreSQL insert on conflict语法以及rule, trigger的功