Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
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 is 2. So return 2.
给出一个数组,数组的度即为出现最多的数字出现的次数,让找出一个子数组和原数组的度一样
思路:
如果只计算数组的度,那么用majority element的投票法就能解决,但是现在要找出一个最短的子数组和原数组的度一样。
而且现在不知道哪个数字出现的次数最多,也可能几个出现次数一样多的要选择一个能使子数组最短的。因此需要一个hashMap来保存每个数字出现的次数。
而且要找到子数组的长度需要知道start index和end index,把每个数字第一次出现的index保存为start index,end index就是现在遍历到的index。
因此另外需要一个hashMap保存start index
当当前遍历到的数字出现的次数等于degree时,就取现有的作为结果的子数组长度和当前index - start index +1中较小的
当遍历到的数字出现的次数>degree时,直接将结果更新到index - start index + 1
这样只要遍历一次就可以了
public int findShortestSubArray(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
HashMap<Integer, Integer> count = new HashMap<>();
HashMap<Integer, Integer> startIdx = new HashMap<>();
int degree = 0;
int result = Integer.MAX_VALUE;
int n = nums.length;
for(int i = 0; i < n; i++) {
int tmp = count.getOrDefault(nums[i], 0);
if(tmp == 0) {
startIdx.put(nums[i], i);
}
count.put(nums[i], tmp+1);
int cnt = count.get(nums[i]);
if(cnt > degree) {
degree = cnt;
result = i-startIdx.get(nums[i]) + 1;
} else if(cnt == degree) {
result = Math.min(result, i-startIdx.get(nums[i]) + 1);
}
}
return result;
}