-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcombineArray.js
More file actions
59 lines (49 loc) · 1.33 KB
/
Copy pathcombineArray.js
File metadata and controls
59 lines (49 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
合并连续区间:[1,2,3,4,1,2,3,6,7,8] => ['1-4','1-3','6-8']
*/
// 使用滑动窗口
function combineArray(arr) {
if (arr.length === 1) return arr;
const re = [];
let start = 0; //滑动窗口开始
let end = 0; //滑动窗口结束
for (let i = 1; i < arr.length; i++) {
if (arr[i - 1] + 1 === arr[i]) {
// 上个元素和当前元素连续
end = i;
} else {
// 上个元素和当前元素不连续,比较start和end,判断应该存储的是单个元素还是合并区间
if (start === end) {
// 存储单个元素
re.push(arr[start]);
} else {
// 存储合并区间
re.push(arr[start] + "-" + arr[end]);
}
// 移动滑动窗口
start = i;
end = i;
}
}
// 存储最后的元素或区间
if (start === end) {
re.push(arr[start]);
} else {
re.push(arr[start] + "-" + arr[end]);
}
return re;
}
// 使用一个指针
function combineArray2(arr) {
let index = 0;
let re = [];
while (index < arr.length) {
let begin = index;
// 遍历直到遇到不连续的元素
while (arr[index] + 1 === arr[index + 1]) index++;
(begin === index && re.push(arr[index])) || re.push(arr[begin] + "-" + arr[index]);
index++;
}
return re;
}
console.log(combineArray2([3, 1, 2, 1, 1, 2, 4, 6, 7, 8, 10]));