Given a non-empty integer array nums that contains only non-negative numbers, the degree of the array is defined as the maximum value of any element in the exponent group. Your task is to find the shortest contiguous sub-array with the same degree as nums and return its length.
Example 1:
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The degree of the input array is 2, because the frequency of elements 1 and 2 is the largest, both of
which have the same degree in consecutive sub-arrays There are as follows:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2
] The length of the shortest contiguous sub-array [2, 2] is 2, so it returns 2.
Example 2:
Input: [1,2,2,3,1,4,2]
Output: 6
Note:
nums.length is in the range of 1 to 50,000.
nums[i] is an integer in the range of 0 to 49,999.
Source: LeetCode
Link: https://leetcode-cn.com/problems/degree-of-an-array
method:
-
If a certain element x has the largest number of occurrences d, then the array from the first occurrence to the last occurrence of this element x is the shortest sub-array.
-
left is the index of the first occurrence of the current element; right is the index of its last occurrence. For example, when nums = [1,2,3,2,5], left[2] = 1 and right[2] = 3.
-
If there are multiple x, then take the smallest right[x]-left[x] + 1
public static int findShortestSubArray(int[] nums) {
Map<Integer, Integer> left = new HashMap(),
right = new HashMap(), count = new HashMap();
for (int i = 0; i < nums.length; i++) {
int x = nums[i];
if (left.get(x) == null) left.put(x, i);
right.put(x, i);
count.put(x, count.getOrDefault(x, 0) + 1);
}
int ans = nums.length;
int degree = Collections.max(count.values());
for (int x : count.keySet()) {
if (count.get(x) == degree) {
ans = Math.min(ans, right.get(x) - left.get(x) + 1);
}
}
return ans;
}