快速的方法来查找多维数组的数组最大? [英] Quick Way to Find the Largest Array in a Multidimensional Array?

查看:107
本文介绍了快速的方法来查找多维数组的数组最大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:我有一个元素的可变数目多维数组。例如。

Situation: I have a multidimensional array with a variable number of elements. e.g.

array(N) {
    0 => array(3) { ... },
    1 => array(8) { ... },
    2 => array(1) { ... },
    ...
    M => array(12) { ... },
    ...
    N-1 => array(7) { ... }
}

和我想找到这个子数组元素的最大数量(在上面的例子中,这将是12)。一个简单的解决方案将是一个O(N)线性搜索。

And I would like to find the maximum number of elements in this sub-array (in the example above, it would be 12). A straightforward solution would be an O(N) linear search.

<?php
function max_length($2d_array) {
    $max = 0;
    foreach($2d_array as $child) {
        if(count($child) > $max) {
            $max = count($child);
        }
    }
    return $max;
}

不过,我不禁在想,如果有一些聪明的把戏来优化这个查询。所以我的问题是两个舞伴(虽然一个答案要么部分将解决它):

However, I can't help but wonder if there's some clever trick to optimize this lookup. So my question is a two-parter (though an answer to either part would solve it):


  • 有没有办法,而不需要特殊的要求比O(N)更快的执行这种搜索算法(pre排序等)?

  • 有一个不起眼的PHP函数的地方,将执行本地code本次搜索,而不是我的userland PHP脚本?

推荐答案

好吧,@DefuseSec在Twitter上是这样说的:

Okay, @DefuseSec on Twitter had this to say:

https://twitter.com/DefuseSec/status/435842054195671040

我倾向于相信这就是这个问题的答案。

I'm inclined to believe that's the answer to this question.

这篇关于快速的方法来查找多维数组的数组最大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆