给定一个非空且只包含非负数的整数数组 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范围内的整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/degree-of-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:用hashmap将数组中个元素出现的频率存在value中,然后找出value中最大的一个或几个值所对应的数组的元素首尾位置+1即为结果。
代码如下:
public int findShortestSubArray(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
int flag=1;
for (int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i])){
map.put(nums[i],map.get(nums[i])+1);
if(map.get(nums[i]) > flag) flag = map.get(nums[i]);
}else{
map.put(nums[i],1);
}
}
int res = nums.length;
for (Integer i:map.keySet()) {
if(map.get(i).equals(flag)){
int start = -1,end = 0;
for (int j = 0; j < nums.length; j++) {
if(i == nums[j] && start == -1){
start = j;
}
if(i == (nums[j]))end = j;
}
if(end - start + 1< res)res = end - start + 1;
}
}
return res;
}
思路2:构建三个容量相同的数组,第一个表示数组出现的频率,第二个表示最先出现位置,第三个表示最后出现位置,坐标表示数组元素。其与思路与上面相同,代码如下:
public int findShortestSubArray(int[] nums) {
int max = 0;
for (int num : nums) {
max = Math.max(max, num);
}
int[] mapSize = new int[max + 1];
int[] mapMin = new int[max + 1];
int[] mapMax = new int[max + 1];
int maxSize = 1;
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
if (mapSize[num] == 0) {
mapMin[num] = i;
mapMax[num] = i;
} else {
mapMax[num] = i;
}
maxSize = Math.max(maxSize, ++mapSize[num]);
}
int ans = Integer.MAX_VALUE;
for (int num = 0; num <= max; num++) {
if (maxSize == mapSize[num]) {
ans = Math.min(ans, mapMax[num] - mapMin[num] + 1);
}
}
return ans;
}