给定一个非空且只包含非负数的整数数组 nums,数组的度的定义是指数组里任一元素出现频数的最大值。你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。
示例 1:
输入:[1, 2, 2, 3, 1]
输出:2
解释:
输入数组的度是2,因为元素1和2的出现频数最大,均为2.
连续子数组里面拥有相同度的有如下所示:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
最短连续子数组[2, 2]的长度为2,所以返回2.
示例 2:
输入:[1,2,2,3,1,4,2]
输出:6
提示:
nums.length 在1到 50,000 区间范围内。
nums[i] 是一个在 0 到 49,999 范围内的整数。
题目的意思就是原数组中出现次数最多的数为A,则和原数组的度相同的最短连续子数组中就有原数组的全部A,且两端恰为A第一次出现和最后一次出现的位置。度相同的数可能有几个,所以要找出最短的连续子数组就需要借助数组或hash表去记录有最大度的数第一次出现的位置和最后一次出现位置的间距。
public int findShortestSubArray(int[] nums) {
int N = 50000;
int n = nums.length;
int[] first = new int[N];//记录值为i第一次出现的位置
int[] last = new int[N];记录值为i最后一次出现的位置
int[] cnt = new int[N];//记录i一共出现了几次
int maxCnt = 0;//记录数组的度
Arrays.fill(first, -1);//将数组进行初始化
for(int i=0;i<n;i++){
int temp = nums[i];
cnt[temp]++;
maxCnt = Math.max(maxCnt, cnt[temp]);
if(first[temp] == -1){
first[temp] = i;
}
last[temp] = i;
}
int result = Integer.MAX_VALUE;
for(int i=0;i<n;i++){
int temp = nums[i];
if(cnt[temp] == maxCnt){
//有几个数值的次数为数组的度,则选取间距最短的
result = Math.min(result, last[temp]-first[temp]+1);
}
}
return result;
}