@@ -94,6 +94,99 @@ function maxEvents(events) {
94
94
}
95
95
96
96
97
+ // another
98
+
99
+ class PriorityQueue {
100
+ constructor ( comparator = ( a , b ) => a > b ) {
101
+ this . heap = [ ]
102
+ this . top = 0
103
+ this . comparator = comparator
104
+ }
105
+ size ( ) {
106
+ return this . heap . length
107
+ }
108
+ isEmpty ( ) {
109
+ return this . size ( ) === 0
110
+ }
111
+ peek ( ) {
112
+ return this . heap [ this . top ]
113
+ }
114
+ push ( ...values ) {
115
+ values . forEach ( ( value ) => {
116
+ this . heap . push ( value )
117
+ this . siftUp ( )
118
+ } )
119
+ return this . size ( )
120
+ }
121
+ pop ( ) {
122
+ const poppedValue = this . peek ( )
123
+ const bottom = this . size ( ) - 1
124
+ if ( bottom > this . top ) {
125
+ this . swap ( this . top , bottom )
126
+ }
127
+ this . heap . pop ( )
128
+ this . siftDown ( )
129
+ return poppedValue
130
+ }
131
+ replace ( value ) {
132
+ const replacedValue = this . peek ( )
133
+ this . heap [ this . top ] = value
134
+ this . siftDown ( )
135
+ return replacedValue
136
+ }
137
+
138
+ parent = ( i ) => ( ( i + 1 ) >>> 1 ) - 1
139
+ left = ( i ) => ( i << 1 ) + 1
140
+ right = ( i ) => ( i + 1 ) << 1
141
+ greater = ( i , j ) => this . comparator ( this . heap [ i ] , this . heap [ j ] )
142
+ swap = ( i , j ) => ( [ this . heap [ i ] , this . heap [ j ] ] = [ this . heap [ j ] , this . heap [ i ] ] )
143
+ siftUp = ( ) => {
144
+ let node = this . size ( ) - 1
145
+ while ( node > this . top && this . greater ( node , this . parent ( node ) ) ) {
146
+ this . swap ( node , this . parent ( node ) )
147
+ node = this . parent ( node )
148
+ }
149
+ }
150
+ siftDown = ( ) => {
151
+ let node = this . top
152
+ while (
153
+ ( this . left ( node ) < this . size ( ) && this . greater ( this . left ( node ) , node ) ) ||
154
+ ( this . right ( node ) < this . size ( ) && this . greater ( this . right ( node ) , node ) )
155
+ ) {
156
+ let maxChild =
157
+ this . right ( node ) < this . size ( ) &&
158
+ this . greater ( this . right ( node ) , this . left ( node ) )
159
+ ? this . right ( node )
160
+ : this . left ( node )
161
+ this . swap ( node , maxChild )
162
+ node = maxChild
163
+ }
164
+ }
165
+ }
166
+ /**
167
+ * @param {number[][] } events
168
+ * @return {number }
169
+ */
170
+ function maxEvents ( events ) {
171
+ const pq = new PriorityQueue ( ( a , b ) => a < b )
172
+ events . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] )
173
+ let res = 0 , i = 0 , n = events . length
174
+ for ( let d = 1 ; d <= 100000 ; d ++ ) {
175
+ while ( i < n && events [ i ] [ 0 ] === d ) {
176
+ pq . push ( events [ i ++ ] [ 1 ] )
177
+ }
178
+ while ( ! pq . isEmpty ( ) && pq . peek ( ) < d ) {
179
+ pq . pop ( )
180
+ }
181
+ if ( ! pq . isEmpty ( ) ) {
182
+ res ++
183
+ pq . pop ( )
184
+ }
185
+ }
186
+ return res
187
+ }
188
+
189
+
97
190
// another
98
191
99
192
0 commit comments