• 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
    
    你的输出为:
    
    ,,,,,,,
  • 相关阅读:
    flutter资料
    flutter兼论
    Dart 学习
    flutter简易教程
    全球15个顶级技术类博客
    Grunt压缩HTML和CSS
    用grunt搭建自动化的web前端开发环境-完整教程
    正确代码之-grunt
    grunt写一个px和rem互转的工具
    unslider使用方法1
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/9063312.html
Copyright © 2020-2023  润新知