隨筆 - 8, 文章 - 0, 評論 - 6, 引用 - 0
          數據加載中……

          實現一個棧,使其push,pop,min(取得棧中的最小元素)均為O(1)

          實現一個棧,使其push,pop,min(取得棧中的最小元素)均為O(1)

          我的解
          interface IntStack
          {
              
          int pop();
              
          void push(int i);
              
          int get();
          }


          class MinStack
          {
              
          //store all the element
              private IntStack elemStack = new IntStack();
              
              
          //store current and historical smallest element
              private IntStack minStack = new IntStack();
              
              
          public void push(int i)
              
          {
                  elemStack.push(i);
                  
                  
          int currentMin = minStack.get();
                  
          if(i <= currentMin) minStack.push(i);
              }

              
              
          public int pop()
              
          {
                  
          int result = elemStack.pop();
                  
          if(result == minStack.get()) minStack.pop();
                  
          return result;
              }

              
              
          public int getMinElem()
              
          {
                  
          return minStack.get();
              }

          }

          posted on 2007-07-18 20:57 Job Hu 閱讀(902) 評論(0)  編輯  收藏 所屬分類: 算法與數據結構

          主站蜘蛛池模板: 永济市| 朔州市| 高州市| 华坪县| 荥阳市| 周至县| 仪陇县| 邢台县| 柳河县| 香河县| 密山市| 内乡县| 江津市| 新宁县| 青神县| 益阳市| 资溪县| 云阳县| 莒南县| 石城县| 胶南市| 寿宁县| 华亭县| 青河县| 唐河县| 徐汇区| 思茅市| 金坛市| 九寨沟县| 桐乡市| 太保市| 上思县| 兴隆县| 奉新县| 英吉沙县| 神池县| 射阳县| 桃源县| 叙永县| 珠海市| 郸城县|