Home  >  Article  >  Backend Development  >  Is there a two-dimensional array merging and deduplication algorithm with O(n) complexity?

Is there a two-dimensional array merging and deduplication algorithm with O(n) complexity?

WBOY
WBOYOriginal
2016-12-05 13:44:141013browse

Is there a two-dimensional array merging and deduplication algorithm with a complexity of O(n)

Is there a two-dimensional array merging and deduplication algorithm with O(n) complexity?

Reply content:

Is there a two-dimensional array merging and deduplication algorithm with a complexity of O(n)

Is there a two-dimensional array merging and deduplication algorithm with O(n) complexity?

<code class="php">$a = [
    ['id'=>1],
    ['id'=>2],
    ['id'=>3],
    ['id'=>4],
    ['id'=>5],
    ['id'=>6]
];
$b = [
    ['id'=>5],
    ['id'=>6],
    ['id'=>7],
];
$c = [
    ['id'=>8],
    ['id'=>9]
];

function array_unique_merge() {
    $params = func_get_args();
    $result = [];
    $hashmap = [];
    $arr_count = count($params);
    for($i = 0; $i<$arr_count; $i++) {
        foreach($params[$i] as $key => $val) {
            $md5 = md5(json_encode($val));
            if (!isset($hashmap[$md5])) {
                $hashmap[$md5] = true;
                $result[] = $val;
            }
        }
    }
    return $result;
}

print_r(array_unique_merge($a, $b, $c));</code>

I just posted my thoughts on how to do this. If n refers to the sum of the number of elements of all arrays.

This must use 2 loops. The definition of n should be the sum of the elements of multiple associative arrays. A double loop is O(n)

Serialize will be used as hash comparison in the future. What about this idea? I won’t write code for mobile phones...

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn