我需要找到包含不超过两个不同数字的数组的最大切片。
这是我的数组[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/