Ask a question to get the starting and ending subscripts of the same value of the array. The array has been sorted

segmentfault 2022-05-15 04:55:52 阅读数:29

askquestionstartingendingsubscripts
let arr = [1,2,2,4,4,4,5,6,6]
// Subscript 0,1,2,3,4,5,6,7,8
// expect Printout rise 1 stop 2 rise 3 stop 5 rise 7 stop 8 



Take the answer 1:

Look at your needs and change them

arr.reduce((res, item, index) => {
if(!res[item]){
let start = arr.indexOf(item)
let end = arr.lastIndexOf(item)
if(start !== end){
res[item] = {start, end}
}
}
return res
}, {})

image.png



Other answers 1:

Look at your needs and change them

arr.reduce((res, item, index) => {
if(!res[item]){
let start = arr.indexOf(item)
let end = arr.lastIndexOf(item)
if(start !== end){
res[item] = {start, end}
}
}
return res
}, {})

image.png


Other answers 2:
let tmp = arr.reduce((acc, cur, idx) => {
acc[cur] = acc[cur] || [];
acc[cur].push(idx);
return acc;
}, {});
let res = Object.values(tmp)
.filter(e => e.length > 1)
.map(e => ` rise ${e[0]} stop ${e[e.length - 1]}`)
.join(' ');
console.log(res);

image.png

There's not only one way .

P.S. Actually, once for Circulation is enough , The above complexity is not optimal , But it's better to have no brain .


Other answers 3:
function findIndexRange (target) {
const ranges = [];
for (
let { [start = 0]: startItem, [pointer = 1]: currentItem, length } = target;
length >= pointer;
currentItem = target[pointer += 1]
) {
if (startItem !== currentItem) {
const end = pointer - 1;
if (start < end) ranges.push([start, end]);
[start, startItem] = [pointer, currentItem];
}
}
return ranges;
}
版权声明:本文为[segmentfault]所创,转载请带上原文链接,感谢。 https://primo.wiki/2022/131/202205111331073573.html