Home >Backend Development >PHP Tutorial >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 a complexity of O(n)
Is there a two-dimensional array merging and deduplication algorithm with a complexity of O(n)
<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...