var arr = [1,2,3,9,9,9,9,6,7,8,10,10,10,15]
var dic = {}
for (k in arr){
if (!dic[arr[k]]){dic[arr[k]] = [k]}
else{dic[arr[k]][1] = k}
}
for (k in dic){if (dic[k].length==1){delete(dic[k])}}
console.log(dic)
{ '9': [ '3', '6' ], '10': [ '10', '12' ] }
@boxsnake
var arr = [1,2,3,9,9,9,9,6,7,9,9,9,8,10,10,10,15,10,10]
var dic = {}
for (k in arr){
k = Number(k)
if(arr[k]==arr[k-1]||arr[k]==arr[k+1]){
if (!dic[arr[k]]){dic[arr[k]] = [[k,k]];continue}
s = dic[arr[k]].slice(-1)[0]
if(k-s[1]==1){s[1]=k}
else{dic[arr[k]].push([k,k])}
}
}
console.log(dic)
@boxsnake
跟 boxsnake 一样是 O(n):
运行结果:
Update
看了其他人的答案里给出了起始和终止的位置,我也来凑个热闹。
运行结果: