在数组中查找最长出现的相同数字 [英] Find longest occurrence of same number in array

查看:146
本文介绍了在数组中查找最长出现的相同数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript,我试图找到一种方法来查找数组中相同数字(在本例中为1)的最长出现次数。

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例如,这是一个示例数组:
[2,5,3,1,1,1,3,7,9,6,4,1,1,1,1,1, 4,7,2,3,1,1,4,3]

For instance, here's a sample array: [2,5,3,1,1,1,3,7,9,6,4,1,1,1,1,1,4,7,2,3,1,1,4,3]

我想写一个会返回的函数 5,因为数字1连续出现5次。 (它也连续出现3次和2次,但我发生的时间最长)。

I'd like to write a function that would return "5", since the number 1 occurs 5 times in a row. (It also occurs 3 and 2 times in a row, but I'm after the longest occurrence).

到目前为止,我已写道:

So far, I have written:

function streak(arr) {
    var i,
        temp,
        streak,
        length = arr.length;

    for(i=0; i<length; i++) {
        if (arr[i] === 1) {
            streak += 1;
        } else {
            temp = streak;
            break;
        }
    }
}

我知道我需要一些方法如果我发现了一个事件,知道我在哪里停下来,但我感觉有点卡住了。

I know I need some way of knowing where I left off if I find an occurrence, but I'm feeling kind of stuck.

任何指针?

推荐答案

我已稍微修改了你的功能。你需要将最高条纹存储为当前条纹的单独变量,并在循环中覆盖必要的变量 - 最后在函数末尾返回该变量。

I've modified your function slightly. You need to store the highest streak as a separate variable from the current streak, and overwrite that where necessary in your loop - finally returning that variable at the end of your function.

function streak(arr) {
    var i,
        temp,
        streak,
        length = arr.length,
        highestStreak = 0;

    for(i = 0; i < length; i++) {
        // check the value of the current entry against the last
        if(temp != '' && temp == arr[i]) {
            // it's a match
            streak++;
        } else {
            // it's not a match, start streak from 1
            streak = 1;
        }

        // set current letter for next time
        temp = arr[i];

        // set the master streak var
        if(streak > highestStreak) {
            highestStreak = streak;
        }
    }

    return highestStreak;
}

var array = [2,5,3,1,1,1,3,7,9,6,4,1,1,1,1,1,4,7,2,3,1,1,4,3];

console.log(streak(array)); // 5

如果你想跟踪的含义最高条纹是,在函数开始时定义另一个变量,保存最高条纹时保存它的值,并将其作为数组返回:

And if you want to also track what the value of the highest streak was, define another variable at the start of your function, save the value of it when you save the highest streak, and return it as an array:

    // set the master streak var
    if(streak > highestStreak) {
        highestStreakValue = temp;
        highestStreak = streak;
    }
}

return [highestStreak, highestStreakValue];


var array = [2,5,3,1,1,1,3,7,9,6,4,'a','a','a','a','a',4,7,2,3,1,1,4,3];
console.log(streak(array)); // [5, "a"]

演示返回两者

Demo returning both

这篇关于在数组中查找最长出现的相同数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆