An array of arbitrary size is given with numbers ranging from 1 to 1,000,000. In this array, all numbers are unique, except for one number, which is repeated two times. Find this number. Solve the problem with minimal use of CPU time.
This is such an interesting task. All ideas are accepted.
This solution came to mind:
$result=array(); $true=true; for($i=0;!$result[$v=$array[$i]]&&$i<ARRAY_ELEMENT_COUNT;$i++){ $result[$v]=&$true; unset($v); } $number=$array[$i];
What other ideas you can apply?
The numbers in the array are mixed:
define('ARRAY_ELEMENT_COUNT',1000); $array=array(); for($index=0;$index<ARRAY_ELEMENT_COUNT;$index++) $array[$index]=$index+1; shuffle($array); //Добавим повторяющийся елемент srand((float)microtime() * 1000000);// эта команда для чистоты эксперимента $pos=&rand(0,ARRAY_ELEMENT_COUNT-1); do{ $val=rand(1,ARRAY_ELEMENT_COUNT-1); }while($array[$pos]==$val); $array[$pos]=$val; unset($val,$pos);