给定一个非空且只包含非负数的整数数组 nums,数组的度的定义是指数组里任一元素出现频数的最大值。你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。
示例 1: 输入:[1, 2, 2, 3, 1] 输出:2 解释: 输入数组的度是2,因为元素1和2的出现频数最大,均为2. 连续子数组里面拥有相同度的有如下所示: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] 最短连续子数组[2, 2]的长度为2,所以返回2.
示例 2: 输入:[1,2,2,3,1,4,2] 输出:6
var findShortestSubArray = function(nums) {
const l = nums.length;
if (l < 2) return l;
const map1 = new Map();
const map2 = new Map();
const map3 = new Map();
let max = 0;
let maxV = [];
for (let i = 0; i < l; i++) {
map1.set(nums[i], (map1.get(nums[i]) || 0) + 1);
map2.set(nums[i], map2.get(nums[i]) === undefined ? i : map2.get(nums[i]));
map3.set(nums[i], i);
if (map1.get(nums[i]) > max) {
max = map1.get(nums[i]);
maxV = [nums[i]];
} else if (map1.get(nums[i]) == max) {
maxV.push(nums[i]);
}
}
console.log(map1);
console.log(map2);
console.log(map3);
return Math.min(...maxV.map((i) => map3.get(i) - map2.get(i) + 1));
};
var arr=[1,2,2,3,1,4,2];
var num=findShortestSubArray(arr);
console.log(num);