Problem Find the smallest positive integer that does not occur in a given sequence.
So what is the best implementation in PHP for this problem of codility!
Solution below results 66%, causing performance issue.
function solution($A)
{
sort($A);
$end = count($A);
$flag = false;
for ($k = 0; $flag == false; $k++, $flag = false) {
for ($i = 0; $i < $end; $i++) {
if ($k + 1 == $A[$i]) {
$flag = $A[$i];
break;
}
}
if($flag == false){
return $k +1;
}
}
}
A simple solution using an associative array as a set:
function solution($A) {
$set = array_flip($A);
for ($n = 1; ; ++$n) {
if (!isset($set[$n])) {
return $n;
}
}
}