Skip to content

Commit 02c1c26

Browse files
authored
Added Find Nearest Point That Has the Same X or Y Coordinate.java
1 parent 0cf730d commit 02c1c26

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public int nearestValidPoint(int x, int y, int[][] points) {
3+
int[] basePoint = new int[]{x, y};
4+
return IntStream.range(0, points.length).mapToObj(i -> new Point(basePoint, i, points[i]))
5+
.filter(
6+
Point::isMatch)
7+
.sorted(Comparator.comparingInt(Point::getManhattanDistance).thenComparing(Point::getIdx))
8+
.map(Point::getIdx).findFirst().orElse(-1);
9+
}
10+
11+
private static class Point {
12+
int[] basePoint;
13+
int idx;
14+
int[] currPoint;
15+
16+
public Point(int[] basePoint, int idx, int[] currPoint) {
17+
this.basePoint = basePoint;
18+
this.idx = idx;
19+
this.currPoint = currPoint;
20+
}
21+
22+
public int getIdx() {
23+
return idx;
24+
}
25+
26+
public int getManhattanDistance() {
27+
return Math.abs(currPoint[0] - basePoint[0]) + Math.abs(currPoint[1] - basePoint[1]);
28+
}
29+
30+
public boolean isMatch() {
31+
return currPoint[0] == basePoint[0] || currPoint[1] == basePoint[1];
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)