给定一个非空且只包含非负数的整数数组 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/degree-of-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
class Solution {
public int findShortestSubArray(int[] nums) {
//找出数组的众数,返回长度间隔最小的
int minLength=Integer.MAX_VALUE,count=Integer.MIN_VALUE;
//int[]{起始位置,末位置,出现的次数};
HashMap<Integer,int[]> startMap=new HashMap<>();
for(int i=0;i<nums.length;i++){
if(!startMap.containsKey(nums[i])){
startMap.put(nums[i],new int[]{i,i,1});
}
else{
startMap.get(nums[i])[1]=i;
startMap.get(nums[i])[2]++;
}
}
for(int i=0;i<nums.length;i++){
if(!startMap.containsKey(nums[i])) continue;
int start=startMap.get(nums[i])[0];
int end=startMap.get(nums[i])[1];
int currentCount=startMap.get(nums[i])[2];
int length=end-start+1;
if(currentCount==count && minLength>length){
minLength=length;
}
else if(currentCount>count){
count=currentCount;
minLength=length;
}
startMap.remove(nums[i]);
}
return minLength==Integer.MAX_VALUE?1:minLength;
}
}