特别注意曼哈顿距离相同时候的边界条件
<?php
class Solution {
/**
* @param int $x
* @param int $y
* @param int[][] $points
* @return int
*/
function nearestValidPoint($x, $y, $points) {
$bestId = -1; // 符合要求的点
$best = 10000; // 曼哈顿距离(根据题目的范围可得理论最大值)
foreach($points as $index => $point) {
if($point[0] == $x) {
$dist = abs($point[1] - $y);
// 严格小于保证取到的一定是下标最小的
if($dist < $best) {
$best = $dist;
$bestId = $index;
}
} elseif ($point[1] == $y) {
$dist = abs($point[0] - $x);
if($dist < $best) {
$best = $dist;
$bestId = $index;
}
}
}
return $bestId;
}
}
$s = new Solution();
$ans = $s->nearestValidPoint(3, 4, [[1,2],[3,1],[2,4],[2,3],[4,4]]);
assert($ans == 2, 'input:3, 4, [[1,2],[3,1],[2,4],[2,3],[4,4]], nearestValidPoint should be 2');
$ans = $s->nearestValidPoint(3, 4, [[3,4]]);
assert($ans == 0, 'input:3, 4, [[3,4]], nearestValidPoint should be 0');
$ans = $s->nearestValidPoint(3, 4, [[2,3]]);
assert($ans == -1, 'input:3, 4, [[2,3]], nearestValidPoint should be -1');