简体   繁体   English

如何在一个数组中找到连续多少次相同的值?

[英]How to find how many times in a row is the same value in an arrray?

Hi I have question how to make algorithm to find how many in a row is the same value in array...嗨,我有疑问如何制作算法来查找数组中连续有多少个相同的值...

My array has 3 values: null, 0-0.99 and 1我的数组有 3 个值:null、0-0.99 和 1

Now I need to find in array how many times in a row is THE LAST value.现在我需要在数组中找到连续多少次是最后一个值。

fe

My array = [null, null, null, 1, 0, 0, 1, 1, 1]我的数组 = [null, null, null, 1, 0, 0, 1, 1, 1]

So I have three 1s as last items in an array how to count them in code?所以我有三个 1 作为数组中的最后一项,如何在代码中计算它们?

If you only want to count how many continuous elements starting from the last one are equal, you can loop backwards like so:如果您只想计算从最后一个开始的连续元素有多少相等,则可以像这样向后循环:

 let arr = [null, null, null, 1, 0, 0, 1, 1, 1]; let last = arr[arr.length - 1]; let count = 1; for(let i = arr.length - 2; i >= 0; i--){ if(arr[i] === last){ ++count; } else break; } console.log(count);

If you want the length of the longest consecutive sequence of numbers equal to the last element of the array, you can loop through the whole array and reset the counter each time the element is not equal to the last one.如果您希望最长连续数字序列的长度等于数组的最后一个元素,则可以循环整个数组并在每次元素不等于最后一个时重置计数器。

 let arr = [null, null, null, 1,1,1,1, 0, 0, 1, 1, 1]; let curr = 0; let maxLen = 1; let last = arr[arr.length - 1]; for(const elem of arr){ if(elem === last) maxLen = Math.max(maxLen, ++curr); else curr = 0; } console.log(maxLen);

 var myArray = [null, null, null, 1, 0, 0, 1, 1, 1]; var needle = myArray[myArray.length-1]; var cnt = 0; var oldCnt = 0; for(let i = 0;i<=myArray.length;i++){ if (myArray[i] == needle){ cnt++; }else{ if (cnt >= oldCnt)oldCnt=cnt; cnt = 0; } } console.log(oldCnt);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM