duandun2218 2013-09-10 09:18
浏览 50
已采纳

如何检查数字2D PHP数组的值是“incereasing”,“descending”还是“mixed”顺序?

I am looking for a method to check if values of a numeric 2D PHP array are in

incereasing , descending , or mixed order.

Example:

array( 1, 2, 3, 4 ) // This is an incereasing numeric array
array( 4, 3, 2, 1 ) // This is a descending numeric array
array( 1, 3, 2, 4 ) // This is a mixed numeric array

How could I check it? ( i am looking for a fast method, it needs to run qickly )

  • 写回答

2条回答 默认 最新

  • du8980919 2013-09-10 09:34
    关注

    I think, if you are looking for quick solution (i.e. works quick), you'll have to work with your data array like:

    function getOrder($rgData)
    {
       if(!count($rgData) || count($rgData)==1)
       {
          return null;
       }
       $sCurrent = (string)array_shift($rgData);
       $iOrder   = current($rgData)>$sCurrent?1:-1;
       foreach($rgData as $mValue)
       {
          if(($sCurrent>(string)$mValue && $iOrder== 1) ||
             ($sCurrent<(string)$mValue && $iOrder==-1))
          {
             return 0;
          }
          $sCurrent = (string)$mValue;
       }
       return $iOrder;
    }
    

    this will return 1,0 and -1 for corresponding ascending, mixed and descending order. Note, that all values will be treated and compared as strings. This method is more useful since it have O(N) complexity (at worst case) while using sort() function will result in O(N log(N)) complexity (at best case)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探