zoukankan      html  css  js  c++  java
  • php实现包含min函数的栈(这个题目用另外一个栈做单调栈的话时间复杂度会低很多)

    php实现包含min函数的栈(这个题目用另外一个栈做单调栈的话时间复杂度会低很多

    一、总结

    这个题目用另外一个栈做单调栈的话时间复杂度会低很多

    二、php实现包含min函数的栈

    题目描述

    定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

    三、代码

    代码一:算法思路:多一个$stackM栈来做单调栈,自然可以很方便取得最小

     1 <?php
     2 $stack = new SplStack(); //1、用的sql库
     3 $stackM = new SplStack(); //2、这个做单调栈
     4  
     5 function mypush($node)
     6 {
     7     // write code here
     8     global $stack;
     9     global $stackM;
    10     $stack->push($node);
    11     if($stackM->isEmpty() || $stackM->top()>$node){
    12         $stackM->push($node);
    13     }
    14 }
    15 function mypop()
    16 {
    17     // write code here
    18     global $stack;
    19     global $stackM;
    20     $node = $stack->pop();
    21     if($node == $stackM->top()){
    22         $stackM->pop();
    23     }
    24     return $node;
    25 }
    26 function mytop()
    27 {
    28     // write code here
    29     global $stack;
    30     return $stack->top();
    31 }
    32 function mymin()
    33 {
    34     // write code here
    35     global $stackM;
    36     return $stackM->top();
    37 }
    

    错误代码:

     1 <?php
     2 
     3 $stack=array();
     4 function mypush($node)
     5 {
     6     $stack[]=$node;
     7 }
     8 function mypop()
     9 {
    10     return array_pop($stack);
    11 }
    12 function mytop()
    13 {
    14     return $stack[count($stack)-1];
    15 }
    16 function mymin()
    17 {
    18     if(empty($stack)) return null;
    19     $min=$stack[0];
    20     for($i=1;$i<count($stack);$i++){
    21         if($min<$stack[$i]) $min=$stack[$i];
    22     }
    23     return $min;
    24 }
    25 return $stack;

    错误提示:

    测试用例:
    ["PSH3","MIN","PSH4","MIN","PSH2","MIN","PSH3","MIN","POP","MIN","POP","MIN","POP","MIN","PSH0","MIN"]
    
    对应输出应该为:
    
    3,3,2,2,2,3,3,0
    
    你的输出为:
    
    ,,,,,,,
  • 相关阅读:
    vue项目中使用定时器,离开页面时清除定时器
    不能在循环中使用res.send(err);
    React使用require加载图片失败
    实验五 单元测试
    实验四 代码评审
    UML 建模工具的安装与使用
    结对编程 第二阶段
    结对编程
    GIT 代码版本管理
    结构化方法与面向对象化方法的比较
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/9063312.html
Copyright © 2011-2022 走看看