码迷,mamicode.com
首页 > 其他好文 > 详细

CC150 3.2

时间:2014-11-24 12:08:38      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:interview

3.2 How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.


Use another stack maintaining min.

push(T t)
{
  mainStack.push(t);
  T curMin = minStack.peek();
  if (curMin == null || t < curMin)
  {
    minStack.push(t);
  }
}

T peek()
{
  return mainStack.peek();
}

T poll()
{
  T t = mainStack.poll();
  if (t == null)
    return t;
  
  if (t == minStack.peek())
    minStack.poll();

  return t;
}

T min()
{
  return minStack();
}


Stack<T> mainStack;
Stack<T> minStack;


CC150 3.2

标签:interview

原文地址:http://7371901.blog.51cto.com/7361901/1581746

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!