Find Nearest Point That Has the Same X or Y Coordinate
给一个点的数组和x,y, 求横坐标或者竖坐标相等的最小距离的点.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Solution { public int nearestValidPoint(int x, int y, int[][] points) { int min = Integer.MAX_VALUE; for(int[] p : points){ if(p[0] == x || p[1] == y) min = Math.min(min, dis(p, x, y)); } for(int i = 0; i < points.length; i++) { if(dis(points[i], x, y) == min && (points[i][0] == x || points[i][1] == y)) return i; } return -1; } private int dis(int[] p, int x, int y) { return Math.abs(p[0] - x) + Math.abs(p[1] - y); } } |