javascript - 查找数组的最大切片 | Javascript

标签 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]);

我不确定下一步要去哪里,我正在努力理解这个问题 - 找到包含不超过两个不同数字的最大切片 - 这让我感到困惑。

最佳答案

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

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

关于javascript - 查找数组的最大切片 | Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42786186/

相关文章:

javascript - 如何在悬停时加载不同的图像

arrays - 将 wchar_t[] 字符串的元素添加到 array<wchar_t>^ 而不使用 for 循环

java - 尽管有足够的可用内存,但巨大的数组仍会耗尽内存

c# - 如何在 C# 中扩展数组

c# - 字符串到字符数组c#导致错误

arrays - 如何连接一个元胞数组(一个数组中有 15 个元胞,每个元胞大约为 1x7500)

javascript - JavaScript for 循环中的 jQuery 不起作用

javascript - HTML5 将外部内容加载到 div 中并使用pushState()?

javascript - 单元测试中通过本地dom访问元素

javascript - 使 Canvas 动画成为父 div 上的背景元素