File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed
src/1054-distant-barcodes Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 28
28
- 10.回溯算法
29
29
491 1498
30
30
31
+ - 11.窗口滑动
32
+ 1054
33
+
31
34
* 字符串
32
35
33
36
* 排序
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } barcodes
3
+ * @return {number[] }
4
+ */
5
+
6
+ // HELP:
7
+ var rearrangeBarcodes = function ( barcodes = [ ] ) {
8
+ if ( barcodes . length <= 2 ) {
9
+ return barcodes ;
10
+ }
11
+ // 数组排序
12
+ barcodes . sort ( ) ;
13
+
14
+ const len = barcodes . length ;
15
+ let mid = Number . parseInt ( len / 2 ) ;
16
+ let listL = undefined ;
17
+ let listR = undefined ;
18
+ let l = 0 ;
19
+ let r = mid ;
20
+ // 如果长度为奇数,则 listL 长度加一
21
+ if ( len % 2 !== 0 ) {
22
+ r = mid + 1 ;
23
+ }
24
+ // 窗口滑动
25
+ while ( r < barcodes . length && barcodes [ r - 1 ] === barcodes [ r ] ) {
26
+ l += 1 ;
27
+ r += 1 ;
28
+ }
29
+ listL = barcodes . slice ( l , r ) ;
30
+ listR = [ ...barcodes . slice ( 0 , l ) , ...barcodes . slice ( r ) ] ;
31
+
32
+ // 新建一个 array,将 listL 和 listR 数据插入其中
33
+ let res = Array ( len ) ;
34
+ for ( let i = 0 ; i < listR . length ; i ++ ) {
35
+ res [ 2 * i ] = listL [ i ] ;
36
+ res [ 2 * i + 1 ] = listR [ mid - 1 - i ] ;
37
+ }
38
+
39
+ if ( len % 2 !== 0 ) {
40
+ res [ len - 1 ] = listL [ mid ] ;
41
+ }
42
+ return res ;
43
+ } ;
You can’t perform that action at this time.
0 commit comments