@@ -14,3 +14,63 @@ const minMoves2 = function(nums) {
14
14
}
15
15
return res ;
16
16
} ;
17
+
18
+ // another
19
+
20
+ /**
21
+ * @param {number[] } nums
22
+ * @return {number }
23
+ */
24
+ const minMoves2 = function ( nums ) {
25
+ const n = nums . length
26
+ const mid = Math . floor ( n / 2 )
27
+ const nth = nthElement ( nums , mid , ( a , b ) => a - b )
28
+ let res = 0
29
+ for ( let i = 0 ; i < n ; i ++ ) {
30
+ res += Math . abs ( nums [ i ] - nth )
31
+ }
32
+
33
+ return res
34
+ }
35
+
36
+ function nthElement ( arr , n , compareFn ) {
37
+ if ( n < 0 || n >= arr . length ) {
38
+ throw new Error ( 'Invalid index' )
39
+ }
40
+
41
+ const partition = ( arr , left , right , pivotIndex ) => {
42
+ const pivotValue = arr [ pivotIndex ]
43
+ ; [ arr [ pivotIndex ] , arr [ right ] ] = [ arr [ right ] , arr [ pivotIndex ] ]
44
+ let storeIndex = left
45
+
46
+ for ( let i = left ; i < right ; i ++ ) {
47
+ if ( compareFn ( arr [ i ] , pivotValue ) < 0 ) {
48
+ ; [ arr [ i ] , arr [ storeIndex ] ] = [ arr [ storeIndex ] , arr [ i ] ]
49
+ storeIndex ++
50
+ }
51
+ }
52
+
53
+ ; [ arr [ right ] , arr [ storeIndex ] ] = [ arr [ storeIndex ] , arr [ right ] ]
54
+ return storeIndex
55
+ }
56
+
57
+ const select = ( arr , left , right , k ) => {
58
+ if ( left === right ) {
59
+ return arr [ left ]
60
+ }
61
+
62
+ let pivotIndex = Math . floor ( Math . random ( ) * ( right - left + 1 ) ) + left
63
+ pivotIndex = partition ( arr , left , right , pivotIndex )
64
+
65
+ if ( k === pivotIndex ) {
66
+ return arr [ k ]
67
+ } else if ( k < pivotIndex ) {
68
+ return select ( arr , left , pivotIndex - 1 , k )
69
+ } else {
70
+ return select ( arr , pivotIndex + 1 , right , k )
71
+ }
72
+ }
73
+
74
+ return select ( arr , 0 , arr . length - 1 , n )
75
+ }
76
+
0 commit comments