File tree 1 file changed +58
-0
lines changed
1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change @@ -47,6 +47,64 @@ var closestRoom = function (rooms, queries) {
47
47
}
48
48
}
49
49
50
+ // another
51
+
52
+ /**
53
+ * @param {number[][] } rooms
54
+ * @param {number[][] } queries
55
+ * @return {number[] }
56
+ */
57
+ const closestRoom = function ( rooms , queries ) {
58
+ const n = rooms . length
59
+ const m = queries . length
60
+ const idxArr = Array . from ( { length : m } , ( _ , i ) => i )
61
+ const res = [ ]
62
+ rooms . sort ( ( a , b ) => b [ 1 ] - a [ 1 ] )
63
+ idxArr . sort ( ( a , b ) => queries [ b ] [ 1 ] - queries [ a ] [ 1 ] )
64
+ const set = new Set ( )
65
+ let j = 0
66
+ for ( let i = 0 ; i < m ; i ++ ) {
67
+ const q = queries [ idxArr [ i ] ]
68
+ while ( j < n && rooms [ j ] [ 1 ] >= q [ 1 ] ) {
69
+ set . add ( rooms [ j ] [ 0 ] )
70
+ j ++
71
+ }
72
+ res [ idxArr [ i ] ] = helper ( q [ 0 ] )
73
+ }
74
+
75
+ return res
76
+
77
+ function helper ( preferedId ) {
78
+ let floor = - Infinity ,
79
+ ceil = Infinity
80
+ for ( const roomId of set ) {
81
+ if ( roomId < preferedId && roomId > floor ) {
82
+ floor = roomId
83
+ }
84
+ if ( roomId >= preferedId && roomId < ceil ) {
85
+ ceil = roomId
86
+ }
87
+ }
88
+ let res = - 1
89
+ if ( floor === - Infinity ) {
90
+ res = ceil
91
+ } else if ( ceil === Infinity ) {
92
+ res = floor
93
+ } else {
94
+ if ( preferedId - floor === ceil - preferedId ) {
95
+ res = floor
96
+ } else if ( preferedId - floor < ceil - preferedId ) {
97
+ res = floor
98
+ } else {
99
+ res = ceil
100
+ }
101
+ }
102
+
103
+ return res === Infinity || res === - Infinity ? - 1 : res
104
+ }
105
+ }
106
+
107
+
50
108
// another
51
109
52
110
/**
You can’t perform that action at this time.
0 commit comments