javascript中最大公共数组切片

时间:2015-01-14 18:02:34

标签: javascript arrays

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

所以,如果我有

[1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 6, 2, 1, 8]

我看的输出是10,因为(0,9)的数组切片是数组的最大切片,不超过两个不同的数字。

我如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

这个例子适合你。但是,我恳请其他更高级编程的神来改进这个或提供另一种解决方案。我认为这段代码可以大大优化。如果您发现此函数返回错误解决方案的错误或示例,请发表评论。

function returnLargestConsecutiveArraySlice(array)
{
    //set an empty array.
    var a = [];
    //walk the supplied array and check if number is not repeated
    array.filter(function (element, index, array) {
    if (element != array[index-1] && element != array[index+1])
    {
        a.push(index);
        return element;
    }
}
);

    //the returned array contains all indexes to the numbers that are not repeated.
    //walk the array and check if number the next number matches the current one.
    //If so the index is consecutive. 
    var numbers = a;
    var b = [[]]; //use an empty array to start with.
    var index = 0;
    for (var i = 0; i < numbers.length-1; i++){
        if(numbers[i+1] == numbers[i]+1)
        {
            //number is consecutive, add.
          b[index].push(numbers[i]);
        }
        else
        {
            //chain broken, start a new one.
            index++;
            b[index] = [];
        }
    }

    //we now have an array with all chains. Look for the largest chain.
    var largest = [];
    for (var i = 0; i < b.length; i++)
    {
        if (b[i].length > largest.length)
        {
            largest = b[i];
        }
    }
    //largest chain found. Slice the original array on the largest chain.
    return array.slice(largest[0], largest[0] + largest.length+1);
}

console.log(returnLargestConsecutiveArraySlice([1, 1, 1, 2, 2, 2, 4, 5, 6, 1, 1, 7, 8, 9, 10, 11, 2, 2, 6, 2, 1, 8]));