File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed
Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[] } arr
3+ * @param {number } target
4+ * @return {number }
5+ */
6+ const findBestValue = function ( arr , target ) {
7+ arr . sort ( ( a , b ) => a - b )
8+ const n = arr . length
9+ const sum = [ ]
10+ sum [ - 1 ] = 0
11+ for ( let i = 0 ; i < n ; i ++ ) sum [ i ] = sum [ i - 1 ] + arr [ i ]
12+ const get = ( x ) => {
13+ // <=x 的最后的位置
14+ let l = - 1 ; let r = n - 1
15+ while ( l < r ) {
16+ const mid = l + r + 1 >> 1
17+ if ( arr [ mid ] > x ) r = mid - 1
18+ else l = mid
19+ }
20+ // [0, l] 不变 [l+1, ) 变成 x
21+ return sum [ l ] + ( n - l - 1 ) * x
22+ }
23+ let l = 0 ; let r = 1e5
24+ while ( l < r ) {
25+ const mid = l + r >> 1
26+ if ( get ( mid ) >= target ) r = mid
27+ else l = mid + 1
28+ }
29+ // 永远小于 target
30+ if ( get ( l ) < target ) return arr [ arr . length - 1 ]
31+ else {
32+ const ans1 = Math . abs ( get ( l ) - target )
33+ const ans2 = Math . abs ( get ( l - 1 ) - target )
34+ if ( ans1 < ans2 ) return l
35+ else return l - 1
36+ }
37+ }
Original file line number Diff line number Diff line change 139139- 2054 . Two Best Non-Overlapping Events
140140- 1235 . Maximum Profit in Job Scheduling
141141- 1751 . Maximum Number of Events That Can Be Attended II
142+ - 1300 . Sum of Mutated Array Closest to Target
142143
143144### 并查集
144145
You can’t perform that action at this time.
0 commit comments