1+ /**
2+ * 1779. Find Nearest Point That Has the Same X or Y Coordinate
3+ *
4+ * x & y = current location
5+ * A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.
6+ * 傳回與目前位置曼哈頓距離最小的有效點的索引(從 0 開始索引)。
7+ * 如果存在多個有效點,則傳回索引最小的有效點。如果沒有有效點,則傳回 -1。
8+ *
9+ * The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).
10+ *
11+ * @param {number } x
12+ * @param {number } y
13+ * @param {number[][] } points
14+ * @return {number }
15+ */
16+ var nearestValidPoint = function ( x , y , points ) {
17+ let ans = - 1 ;
18+ let smallest = Infinity ;
19+ for ( let i = 0 ; i < points . length ; ++ i ) {
20+ let prev = Math . abs ( x - parseInt ( points [ i ] [ 0 ] ) ) ;
21+ let next = Math . abs ( y - parseInt ( points [ i ] [ 1 ] ) ) ;
22+ if ( prev * next === 0 && ( prev + next ) < smallest ) {
23+ smallest = prev + next ;
24+ ans = i ;
25+ }
26+
27+ }
28+ return ans ;
29+ } ;
30+ // let x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]];
31+ // 2
32+ // Of all the points, only [3,1], [2,4] and [4,4] are valid.
33+ // Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1.
34+ // [2,4] has the smallest index, so return 2.
35+
36+ // let x = 3, y = 4, points = [[3,4]];
37+ // 0
38+ // let x = 3, y = 4, points = [[2,3]];
39+ // -1
40+
41+ let x = 5 , y = 1 , points = [ [ 1 , 1 ] , [ 6 , 2 ] , [ 1 , 5 ] , [ 3 , 1 ] ] ;
42+ // 3
43+ console . log ( nearestValidPoint ( x , y , points ) ) ;
0 commit comments