在数组 JavaScript 中查找子数组的度
javascriptweb developmentfront end technologyobject oriented programming
文字数组的度定义为其任意一个元素的最大频率。
const arr = [1, 2, 3, 3, 5, 6, 4, 3, 8, 3];
此数组的度为 4,因为 3 在此数组中重复了 4 次。
我们需要编写一个 JavaScript 函数,该函数接受文字数组。我们的函数的任务是从数组中找到度与整个数组相同的最小连续子数组的长度。
示例
const arr = [1, 2, 3, 3, 5, 6, 4, 3, 8, 3]; const findShortestSubArray = (arr = []) => { let range = new Map(), maxDegree = 0, minLength = Infinity; for(let i = 0; i < arr.length; i++){ if(range.has(arr[i])) { let start = range.get(arr[i])[0]; let degree = range.get(arr[i])[2]; degree++; range.set(arr[i], [start, i, degree]); if(degree > maxDegree) maxDegree = degree; } else { let degree = 1; range.set(arr[i],[i, i, degree]); if(degree > maxDegree) maxDegree = degree; } } for (let key of range.keys()){ let val = range.get(key) if(val[2] === maxDegree){ let diff = (val[1] - val[0]) + 1; if(diff < minLength) minLength = diff; } } return minLength; }; console.log(findShortestSubArray(arr));
输出
控制台中的输出将是 −
8