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: [1, 2, 2, 3, 1]
Output: 2
Explanation:
輸入數組的度爲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。
Example 2:
Input: [1,2,2,3,1,4,2]
Output: 6this
public int findShortestSubArray(int[] nums) { int minLength = nums.length; int degree = 0; HashMap<Integer, Integer> count = new HashMap<Integer,Integer>(); HashMap<Integer,Integer[]> index = new HashMap<Integer,Integer[]>(); for(int i=0;i<nums.length;i++){ count.put(nums[i], count.getOrDefault(nums[i], 0) + 1); degree = Math.max(degree, count.get(nums[i])); if(index.get(nums[i]) == null){ index.put(nums[i],new Integer[2]); } Integer[] numRange = index.get(nums[i]); if(numRange[0] == null)numRange[0] = i; numRange[1] = i; } for(Map.Entry<Integer, Integer> entry : count.entrySet()){ if(entry.getValue() != degree){ continue; } Integer[] range = index.get(entry.getKey()); minLength = Math.min(minLength, range[1]-range[0]+1); } return minLength; }