Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

面试题30 是否有必要总是将min(value, m_min.top())压入辅助栈中? #77

Open
Jaxx4Fun opened this issue Mar 23, 2020 · 1 comment

Comments

@Jaxx4Fun
Copy link

Jaxx4Fun commented Mar 23, 2020

template <typename T> void StackWithMin<T>::push(const T& value)
{
    // 把新元素添加到辅助栈
    m_data.push(value);

    // 当新元素比之前的最小元素小时,把新元素插入辅助栈里;
    // 否则把之前的最小元素重复插入辅助栈里
   // jun: 除非当前元素小于或等于min,否则不插入辅助栈
    if(m_min.size() == 0 || value <= m_min.top())
        m_min.push(value);
    // else
    //    m_min.push(m_min.top());
}

template <typename T> void StackWithMin<T>::pop()
{
    assert(m_data.size() > 0 && m_min.size() > 0);
    if( m_data.top() == m_min.top() )
    {
        m_min.pop();
    }
}

这样更加节省空间一点,逻辑判断应该也还好吧

@Jaxx4Fun Jaxx4Fun reopened this Apr 4, 2020
@gyzcool
Copy link

gyzcool commented Feb 1, 2021

嗯嗯,leetcode155 最小栈,有些人就用的这种方法,节约点空间。 你那个 pop的时候只pop了栈m_min,漏掉了m_data栈。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants