Find longest occurrence of same number in array

前端 未结 12 1511
一生所求
一生所求 2021-01-05 17:49

Using JavaScript, I\'m trying to find a way to find the longest occurrence of the same number (in this case, 1) in an array.

For instance, here\'s a sample array:

12条回答
  •  轮回少年
    2021-01-05 17:54

    My proposal:

    function getLongestRow(inputArray) {
        // Initialize dummy variables
        var start = inputArray[0], curRowLen = 0, maxRowLen = 0, maxRowEle = 0;
    
        // Run through the array
        for(var i = 0;i < inputArray.length;i++) {
            // If current Element does not belong to current row
            if(inputArray[i] != start) {
                // If current row is longer than previous rows, save as new longest row
                if(curRowLen > maxRowLen) {
                    maxRowLen = curRowLen;
                    maxRowEle = start;
                    curRowLen = 1;
                }
                // Start new row
                start = inputArray[i];
            } else {
                // Current element does belongt to current row, increase length
                curRowLen++;
            }
        }
    
        // Check whether last row was longer than previous rows
        if(curRowLen > maxRowLen) {
            maxRowLen = curRowLen;
            maxRowEle = start;
        }
    
        // Return longest row & element longest row consits of
        console.log('The longest row in your array consists of '+maxRowLen+' elements of '+maxRowEle+'.');
    }
    

    JsFiddle: http://jsfiddle.net/hdwp5/

提交回复
热议问题