用PHP刷LintCode算法题----视野争夺
题目: 链接
题解
class StatAnchorAnalysisController extends Backend
{
public $sum = 0;
/**
* Lists all StatAnchorAnalysis models.
* @return mixed
*/
public function actionIndex()
{
$pos = [[0,2],[0,1],[2,4],[4,5]];
$length =5;
var_dump($this->actionGetMiniumVisionWard($pos,$length,0));exit;
}
public function actionGetMiniumVisionWard($pos=[],$length=0,$left_length=0){
//判断数组右边界是否大于等于当前长度
$right_boundary = array_column($pos,1);
array_multisort($right_boundary,SORT_DESC,$pos);
if ($pos[0][1]<$length){
return -1;
}
//判断数组左边界是否小于等于0
$left_boundary = array_column($pos,0);
array_multisort($left_boundary,SORT_ASC,$pos);
if ($pos[0][0]>$left_length){
return -1;
}
$unset_arr = [];
foreach ($pos as $k=>$v){
if ($v[0]<=$left_length){
$unset_arr[] = $v;
}
}
//拿到左边界小于等于零的最大长度守卫
$unset_length = 0;
$unset = [];
foreach ($unset_arr as $k=>$v){
if ($v[1]-$v[0]>$unset_length){
$unset = $v;
$unset_length = $v[1]-$v[0];
}
}
$this->sum++;
if ($unset_length>=$length){
return $this->sum;
}else{
unset($pos[array_search($unset,$pos)]);
$this->actionGetMiniumVisionWard($pos,$length-$unset_length,$unset[1]);
}
return $this->sum;
}
}