开发者

search through array and find 1 couple optimally?

Let`s suppose we have a simple (non-assoc) array with 100001 values and these values set in unsorted order like 45, 12, 32, 23. We know that in this array is 1 couple of numbers, how to find it optimally - not via 2 foreach loops and even not via 2 for loops with 1开发者_运维百科00001/2 division?


Use array_count_values:

$result=array_count_values($arr);
$value=array_search(2, $result);

print $value;


Since your array is not sorted, the ONLY search method other than random scatteryshot is to scan the array sequentially and look for your two numbers:

$first_key = null;
$second_key = null;

foreach($array as $key => $val) {
    if ($val == $first_number) {
       $first_key = $key;
    }
    if ($val == $second_number) {
       $second_key = $key;
    }
    if (!is_null($first_key) && !is_null($second_key)) {
        break;
    }
}

Once both numbers are found, or you reach the end of the array, the loop will exit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜