image.png
array_intersect实现了这个方法,我不知道是否可以先排序。
第一个反应是嵌入双层循环,但需要时间的复杂性。 但是,先至少排序NlogN,再加上n。
果然比NN强吧。
取差集合后,集合中的元素顺序不是以前的顺序。
求大人物的最优解
类集{
publicstaticfunctionintersect ($ a、$b、$c=null ) )。
if(is_null($c ) ) {
$c=function($a,$b ) {return $a - $b; (;
}
self:3360qsort($a,$c );
self:qsort($b,$c;
//var_dump($a; var_dump($b;
$ans=[];
for($I=0,$j=0; isset($a($I ) ) isset ($ b ) $j ); () )。
if($c ) $b[$j],$b[$j] )==0) {
array_push($ans,$a[$i];
$j =1;
$i =1;
}elseif($c ) $b[$j],$b[$j] )0) {
//printf(I=%d,j=%d,a[i]=%d,b[j]=%dn ',$i,$j,$a[$i],$b[$j] );
$i =1;
} else {
$j =1;
}
}
返回$ ans;
}
publicstaticfunctionminus($a、$b、$c=null ) )。
if(is_null($c ) ) {
$c=function($a,$b ) {return $a - $b; (;
}
self:3360qsort($a,$c );
self:qsort($b,$c;
$ans=[];
for($I=0,$j=0; isset($a($I ) ) isset ($ b ) $j ); () )。
if($c ) $b[$j],$b[$j] )==0) {
$j =1;
$i =1;
}elseif($c ) $b[$j],$b[$j] )0) {
//printf(I=%d,j=%d,a[i]=%d,b[j]=%dn ',$i,$j,$a[$i],$b[$j] );
array_push($ans,$a[$i];
$i =1;
} else {
$j =1;
}
}
返回$ ans;
}
publicstaticfunctionqsort (array $ a,callable $c ) {
self:3360_qsort($a,0,count ) $a )-1,$c );
}
私有状态_ qsort (array $ a、int $low、int $high、callable $c ) {
if($low=$high ) {
返回;
}
$first=$low;
$last=$high;
$pivot=$a[$first];
wile($first$last ) {
wile$first$last$c$a[$last],$pivot]=0) {
$last -=1;
}
$a[$first]=$a[$last];
wile($first$last$c ) $pivot,$a[$first] )=0) {
$first =1;
}
$a[$last]=$a[$first];
}
$a[$first]=$pivot;
self:3360_qsort($a、$low、$first-1、$c );
self:3360_qsort($a,$first 1,$high,$c );
}
publicstaticfunctiontostring ($ a ) {
if (! isset($a[0] ) {return ' ); }
$s='['.$a[0];
for($I=1; $Icount($a ); $i =1
$s .=','.$a[$i];
}
return$s.' ';
}
}
$ a=[ 4,61,46,15,59,95,26,90,53,54,53 ];
$ b=[ 76,3100,54,27,37,89,49,55,378,32,15 ];
//set:3360qsort($a,function ) $a,$b ) {return $a - $b; );
//Foreach($aas$it ) ) { echo $it.','; } echo 'n ';
//set:3360qsort($b,function ) $a,$b ) {return $a - $b; );
//var_dump($a;
$c=set:3360intersect($a,$b );
ECHOset:3360tostring($c ).PHP_EOL;
$d=set:3360minus($a,$b );
ECHOset:3360tostring($d ).PHP_EOL;