File tree Expand file tree Collapse file tree 3 files changed +73
-0
lines changed
solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II Expand file tree Collapse file tree 3 files changed +73
-0
lines changed Original file line number Diff line number Diff line change @@ -274,6 +274,32 @@ function minSwaps(nums: number[]): number {
274
274
};
275
275
```
276
276
277
+ #### JavaScript
278
+
279
+ ``` js
280
+ function minSwaps (nums ) {
281
+ const n = nums .length ;
282
+
283
+ const getMin = x => {
284
+ const prefixSum = Array (n + 1 ).fill (0 );
285
+ for (let i = 1 ; i <= n; i++ ) {
286
+ prefixSum[i] = prefixSum[i - 1 ] + (nums[i - 1 ] === x);
287
+ }
288
+
289
+ const length = prefixSum[n];
290
+ let ans = Number .POSITIVE_INFINITY ;
291
+ for (let l = 0 , r = length; r <= n; l++ , r++ ) {
292
+ const min = length - (prefixSum[r] - prefixSum[l]);
293
+ ans = Math .min (ans, min);
294
+ }
295
+
296
+ return ans;
297
+ };
298
+
299
+ return Math .min (getMin (0 ), getMin (1 ));
300
+ }
301
+ ```
302
+
277
303
<!-- tabs: end -->
278
304
279
305
<!-- solution: end -->
Original file line number Diff line number Diff line change @@ -276,6 +276,32 @@ function minSwaps(nums: number[]): number {
276
276
};
277
277
```
278
278
279
+ #### JavaScript
280
+
281
+ ``` js
282
+ function minSwaps (nums ) {
283
+ const n = nums .length ;
284
+
285
+ const getMin = x => {
286
+ const prefixSum = Array (n + 1 ).fill (0 );
287
+ for (let i = 1 ; i <= n; i++ ) {
288
+ prefixSum[i] = prefixSum[i - 1 ] + (nums[i - 1 ] === x);
289
+ }
290
+
291
+ const length = prefixSum[n];
292
+ let ans = Number .POSITIVE_INFINITY ;
293
+ for (let l = 0 , r = length; r <= n; l++ , r++ ) {
294
+ const min = length - (prefixSum[r] - prefixSum[l]);
295
+ ans = Math .min (ans, min);
296
+ }
297
+
298
+ return ans;
299
+ };
300
+
301
+ return Math .min (getMin (0 ), getMin (1 ));
302
+ }
303
+ ```
304
+
279
305
<!-- tabs: end -->
280
306
281
307
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ function minSwaps ( nums ) {
2
+ const n = nums . length ;
3
+
4
+ const getMin = x => {
5
+ const prefixSum = Array ( n + 1 ) . fill ( 0 ) ;
6
+ for ( let i = 1 ; i <= n ; i ++ ) {
7
+ prefixSum [ i ] = prefixSum [ i - 1 ] + ( nums [ i - 1 ] === x ) ;
8
+ }
9
+
10
+ const length = prefixSum [ n ] ;
11
+ let ans = Number . POSITIVE_INFINITY ;
12
+ for ( let l = 0 , r = length ; r <= n ; l ++ , r ++ ) {
13
+ const min = length - ( prefixSum [ r ] - prefixSum [ l ] ) ;
14
+ ans = Math . min ( ans , min ) ;
15
+ }
16
+
17
+ return ans ;
18
+ } ;
19
+
20
+ return Math . min ( getMin ( 0 ) , getMin ( 1 ) ) ;
21
+ }
You can’t perform that action at this time.
0 commit comments