Does the array have a unique element?

I am looking for the most efficient algorithm to check if an array has a unique element in it. The result may not be a unique element, but true or false. I know that I can achieve O (n) efficiency with a hash table or somesuch, but I'm still looking for a result that is also more efficient in size.

The e-array is unsorted and contains integers.

+5
source share
5 answers

I come to your question after reading all the comments, This is an algorithm without extra space and O (n).

XORing , XOR - . 0, , else result XOR , TRUE.

(. http://codepad.org/qyzT1v4N):

<?php


function testUnique($arr){
  $res = 0;
  for($i=0;$i< count($arr);$i++)
{
   $res ^= $arr[$i];
}
 return ($res != 0);
}

$dup = array(1,1,3,3,2,2);
var_dump(testUnique($dup));

$dup = array(6,6,4,3,2,2);
var_dump(testUnique($dup));
?>
+1

, - ( O (n) , O (n) , -).

, , , - ( O (n), -, -) ( O (n * lg (n) , O (n) )

, , , , , Bloom Filter. Bloom , -, ( , , )

+1

O (n), O (n ^ 2)

0

array_keys() php.

array array_keys ( array $input [, mixed $search_value [, bool $strict = false ]] )

$search_value, . , .

, ( ) . .:)

[]: , , array_keys() - O (n).

0

:

1) : O (n ^ 2), O (1).

2a) : O (nlogn) , : O (1). 2b) (radix, counting,...) : O (n), O (n)

3) A hash table or array for storing membership: O (n) time, O (n) space.

Basically, you should choose either 2a (space) or 3.

0
source

All Articles