Input: nums =[1,2,2,3,1] Output:2 Explanation: The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree:[1,2,2,3,1],[1,2,2,3],[2,2,3,1],[1,2,2],[2,2,3],[2,2] The shortest length is2. So return2.
Input: nums =[1,2,2,3,1,4,2] Output:6 Explanation: The degree is3 because the element 2is repeated 3 times. So [2,2,3,1,4,2]is the shortest subarray, therefore returning 6.
To find the shortest subarray with the same degree as the original array, we need to know the frequency (degree) of each element and the first and last positions where each element appears. The answer is the minimum length among all elements with maximum frequency.
classSolution {
funfindShortestSubArray(nums: IntArray): Int {
val cnt = mutableMapOf<Int, Int>()
val first = mutableMapOf<Int, Int>()
val last = mutableMapOf<Int, Int>()
for ((i, x) in nums.withIndex()) {
cnt[x] = cnt.getOrDefault(x, 0) + 1if (x !in first) first[x] = i
last[x] = i
}
val deg = cnt.values.maxOrNull() ?:0var ans = nums.size
for ((k, v) in cnt) {
if (v == deg) {
ans = minOf(ans, last[k]!! - first[k]!! + 1)
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
deffindShortestSubArray(self, nums: list[int]) -> int:
cnt: dict[int, int] = {}
first: dict[int, int] = {}
last: dict[int, int] = {}
for i, x in enumerate(nums):
cnt[x] = cnt.get(x, 0) +1if x notin first:
first[x] = i
last[x] = i
deg: int = max(cnt.values())
ans: int = len(nums)
for x in cnt:
if cnt[x] == deg:
ans = min(ans, last[x] - first[x] +1)
return ans