给定一个非空且只包含非负数的整数数组 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
解:
/*
解题思路:
1、先求出数组的度
2、在求出与数组拥有相同大小度的最短连续子数组
关键:建立一个map,每个map包含一个长度为3的数组
arr[0]:代表起始位置
arr[1]:代表最后一次出现的位置
arr[2]:出现的次数
*/
class Solution {
public int findShortestSubArray(int[] nums) {
Map<Integer,int[]> tempMap = new HashMap<Integer,int[]>();
int deg = 1;
for(int i=0;i<nums.length;i++){
if(tempMap.containsKey(nums[i])){
int[] value = tempMap.get(nums[i]);
value[1]=i;//更新终止位置
int tempValue = value[2]+1;
value[2]=tempValue;
System.out.println("tempValue="+tempValue);
deg=Math.max(deg,tempValue);
}else{
int[] arr = new int[3];
arr[0] = i;
arr[1] = i;
arr[2] = 1;
tempMap.put(nums[i],arr);
}
}
System.out.println("deg="+deg);
//遍历map,找出最小长度
int minlen=0;
for(Integer key:tempMap.keySet()){
int[] arr = tempMap.get(key);
if(arr[2]==deg){//如果为最大度数
if(minlen==0)
minlen = arr[1]-arr[0];
minlen = Math.min(minlen,arr[1]-arr[0]);
}
}
return minlen+1;
}
}
public class MainClass {
public static int[] stringToIntegerArray(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if (input.length() == 0) {
return new int[0];
}
String[] parts = input.split(",");
int[] output = new int[parts.length];
for(int index = 0; index < parts.length; index++) {
String part = parts[index].trim();
output[index] = Integer.parseInt(part);
}
return output;
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
int[] nums = stringToIntegerArray(line);
int ret = new Solution().findShortestSubArray(nums);
String out = String.valueOf(ret);
System.out.print(out);
}
}
}