从包含正整数和/或递归嵌套正整数数组的数组中查找最大值

Moh*_*lam 1 php arrays max

如果数组初始化为:

   $arr = array(array(141,151,161),2,3,array(101,102,array(303,404,606,555,789,array(1000,22,9999,array(9057,100000),522))));
Run Code Online (Sandbox Code Playgroud)

那么结果应该是:100000

我已经写了一个函数来解决这个问题,但我需要更少的字节和更少的代码内存.

我的职责是:

function MaxArray($arr){
$length = count($arr);
global $maxValue;
for($i=0;$i<$length;$i++){
        if(is_int($arr[$i])){

                if($maxValue < $arr[$i]){
                    $maxValue = $arr[$i];
                }

        }
        elseif(is_array($arr[$i])){     
                MaxArray($arr[$i]);
            }
        }
    return $maxValue;   
}
Run Code Online (Sandbox Code Playgroud)

Lev*_*son 5

摘自PHP手册,但由我撰写:

/**
 * @param array $array
 *
 * @return int|null Returns the largest value of the array. Returns NULL if no 
 *     integers are found.
 */
function array_max_recursive(array $array) {
    $max = NULL;
    $stack = array($array);

    do {
        $current = array_pop($stack );
        foreach ($current as $value) {
            if (is_array($value)) {
                $stack[] = $value;
            } elseif (filter_var($value, FILTER_VALIDATE_INT) !== FALSE) {
                // max(NULL, 0) returns NULL, so cast it
                $max = (int) max($max, $value);
            }
        }

    } while (!empty($stack));

    return $max;
}
Run Code Online (Sandbox Code Playgroud)
  • 此函数实际上不是递归的,但满足了它在子数组上工作的要求.我不喜欢没有运行时堆栈的事情.
  • 它返回int类型的东西,而不是int的字符串表示形式.例外情况是您提供的数组不包含任何整数.然后它将返回NULL.
  • 它忽略非数组,非int值.