查找最大切片数组|Java脚本 [英] Find Max Slice Of Array | Javascript

查看:92
本文介绍了查找最大切片数组|Java脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to find the maximum slice of the array which contains no more than two different numbers.

这是我的数组 [1、1、1、2、2、2、1、1、2、2、6、2、1、8]

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

My thought process on this is to find the numbers that are not repeated and return their index within a new array.

这是我到目前为止所拥有的:

Here is what I have so far:

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

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

I'm unsure where to go next, I'm struggling to understand the question that being - find the maximum slice which contains no more than two different numbers - that confuses me.

推荐答案

一个循环的解决方案,它检查最后的值并增加一个计数器.

A solution with a single loop, which checks the last values and increments a counter.

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

这篇关于查找最大切片数组|Java脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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