找出数组中连续重复元素的起始索引?

var arr = [1,2,3,9,9,9,9,6,7,8,10,10,10,15]

找出连续重复元素的起始索引,求一个复杂度较低的算法?


慕容708150
浏览 520回答 1
1回答

12345678_0001

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' ] }@boxsnakevar 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){ '9': [ [ 3, 6 ], [ 9, 11 ] ],  '10': [ [ 13, 15 ], [ 17, 18 ] ] }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript