我的要求是找到一个数组中的最大值/最大值,其中可能包含其他数组。例如,我们可以查看下面的数组。
$array =
array(
13,
array(10, 4, 111, 3),
4,
array(23, 450, 12,array(110, 119, 20, 670), 45 ,45,67,89),
);
$max = find_max($array, 0);
print "Maximumum Value is $max";
我已经有了一个工作函数 find_max,但我只想知道除了下面给出的代码之外,还有什么最好和最有效可能的方法来做到这一点。
function find_max($array, $maxValue) {
foreach ($array as $member) {
if (is_array($member)) {
$maxValue = find_max($member, $maxValue);
} else {
if($member==$maxValue){
continue;
}
if ($member > $maxValue) {
$maxValue = $member;
}
}
}
return $maxValue;
}
最佳答案
您找不到比 O(n) 或 linear time 更快的数组(或数组的数组)的最大值.
如果您需要不断地找到这个数组的最大值,我建议您对数组进行排序,或者尽可能使用不同的(排序的)数据结构。
您还可以保留对最大值的引用并在插入数据时更新它。显然,这是假设您自己插入数据而不是从其他地方获取数据,在这种情况下,我最后的评论对您来说毫无用处。
关于php - 查找数组中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12016084/