gpt4 book ai didi

php - 如何检查数字 2D PHP 数组的值是否为 'incereasing' 、 'descending' 或 'mixed' 顺序?

转载 作者:行者123 更新时间:2023-12-04 04:42:18 25 4
gpt4 key购买 nike

我正在寻找一种方法来检查数字 2D PHP 数组的值是否在

递增 ,
降序 ,

混合 订单。

示例:

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

我怎么查? (我正在寻找一种快速的方法,它需要快速运行)

最佳答案

我认为,如果您正在寻找快速解决方案(即快速工作),您将不得不使用您的数据数组,例如:

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;
}

这将为相应的升序、混合和降序返回 1,0 和 -1。请注意,所有值都将作为字符串进行处理和比较。这个方法更有用,因为它有 O(N)使用 sort() 时的复杂性(在最坏的情况下)函数将导致 O(N log(N))复杂性(最好的情况)

关于php - 如何检查数字 2D PHP 数组的值是否为 'incereasing' 、 'descending' 或 'mixed' 顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18715028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com