zoukankan      html  css  js  c++  java
  • 包含min函数的栈

    定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

    由于本身给了import java.util.Stack;所以感觉可以使用JDK自带的栈

    思路:用两个栈进行记录,s1记录全部,s2记录各个时刻最小值

    源码如下:

     1 import java.util.Stack;
     2 
     3 public class Solution {
     4 
     5     Stack<Integer> s1 = new Stack();
     6     Stack<Integer> s2 = new Stack();
     7     
     8     public void push(int node) {
     9         s1.push(node);
    10         if(s2.empty())
    11             s2.push(node);
    12         else{
    13             if(node<s2.peek())
    14                 s2.push(node);
    15         }
    16     }
    17     
    18     public void pop() {
    19         if(s1.peek()==s2.peek()){
    20             s1.pop();
    21             s2.pop();
    22         }else{
    23             s1.pop();
    24         }
    25     }
    26     
    27     public int top() {
    28         return s1.peek();
    29     }
    30     
    31     public int min() {
    32         return s2.peek();
    33     }
    34 }
  • 相关阅读:
    oracle-sql脚本
    vue生命周期
    使用vue搭建项目(创建手脚架)
    bootcss
    miniMobile(手机)
    mui(手机)
    layui
    Element
    如何学好Spring
    使用Vue做评论+localStorage存储(js模块化)
  • 原文地址:https://www.cnblogs.com/haq123/p/12181653.html
Copyright © 2011-2022 走看看