找到最大切片数组| 使用Javascript

Fil*_*lth 5 javascript arrays

我需要找到包含不超过两个不同数字的数组的最大切片.

这是我的阵列 [1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 6, 2, 1, 8]

我的思考过程就是找到不重复的数字并在新数组中返回它们的索引.

这是我到目前为止:

function goThroughInteger(number) {
    var array = [];
    //iterate the array and check if number is not repeated   
  number.filter(function (element, index, number) {
    if(element != number[index-1] && element != number[index+1]) {
        array.push(index);
      return element;
    }
  })

    console.log(array);
}
goThroughInteger([1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 6, 2, 1, 8]);
Run Code Online (Sandbox Code Playgroud)

我不确定下一步该去哪里,我很难理解存在的问题 - 找到包含不超过两个不同数字的最大切片 - 这让我感到困惑.

Nin*_*olz 5

具有单个循环的解决方案,其检查最后的值并递增计数器.

function getLongestSlice(array) {
    var count = 0,
        max = 0,
        temp = [];

    array.forEach(function (a) {
        var last = temp[temp.length - 1];

        if (temp.length < 2 || temp[0].value === a || temp[1].value === a) {
            ++count;
        } else {
            count = last.count + 1;
        }
        if (last && last.value === a) {
            last.count++;
        } else {
            temp.push({ value: a, count: 1 });
            temp = temp.slice(-2);
        }
        if (count > max) {
            max = count;
        }
    });
    return max;
}

console.log(getLongestSlice([58, 800, 0, 0, 0, 356, 8988, 1, 1]));        //  4
console.log(getLongestSlice([58, 800, 0, 0, 0, 356, 356, 8988, 1, 1]));   //  5
console.log(getLongestSlice([1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 6, 2, 1, 8])); // 10
Run Code Online (Sandbox Code Playgroud)