JavaScript数组的子数组度数
文本数组的度数定义为其任何一个元素的最大频率。
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
广告