Skip to content

Commit 49eb9db

Browse files
committed
✨ distant barcodes
1 parent 7654465 commit 49eb9db

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

CATEGORY.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@
2828
- 10.回溯算法
2929
491 1498
3030

31+
- 11.窗口滑动
32+
1054
33+
3134
* 字符串
3235

3336
* 排序

src/1054-distant-barcodes/index.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
};

0 commit comments

Comments
 (0)