
😎풀이
frequent
: 등장한 숫자의 빈도
nums
순회하며 각 숫자의 빈도를 구함
maxFreq
: 최빈값을 구함
shortestLen
: 최소 서브 어레이의 길이
nums
를 순회
5-1. curLen
: 현재 값이 최빈값이라면, 시작 지점과 끝 지점을 통해 길이를 구함
5-2. 현재 최소 길이와 비교하여 최소 길이 탐색
- 탐색된 최소 길이(
shortestLen
) 반환
function findShortestSubArray(nums: number[]): number {
const frequent = new Map<number, number>()
for(const num of nums) frequent.set(num, (frequent.get(num) ?? 0) + 1)
const maxFreq = Math.max(...[...frequent.values()])
let shortestLen = Infinity
for(const num of nums) {
if(frequent.get(num) < maxFreq) continue
const curLen = nums.lastIndexOf(num) - nums.indexOf(num) + 1
shortestLen = Math.min(shortestLen, curLen)
}
return shortestLen
};