做题博客链接
https://blog.youkuaiyun.com/qq_43349112/article/details/108542248
题目链接
https://leetcode-cn.com/problems/degree-of-an-array/
描述
给定一个非空且只包含非负数的整数数组 nums,数组的度的定义是指数组里任一元素出现频数的最大值。
你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。
提示:
nums.length 在1到 50,000 区间范围内。
nums[i] 是一个在 0 到 49,999 范围内的整数。
示例
示例 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
初始代码模板
class Solution {
public int findShortestSubArray(int[] nums) {
}
}
代码
class Solution {
public int findShortestSubArray(int[] nums) {
Map<Integer, int[]> map = new HashMap<>();
int res = nums.length;
int times = 0;
for (int i = 0; i < nums.length; i++) {
int[] cur = new int[]{1, i};
if (map.containsKey(nums[i])) {
cur = map.get(nums[i]);
cur[0]++;
}
if (cur[0] > times) {
times = cur[0];
res = i - cur[1] + 1;
} else if (cur[0] == times) {
res = Math.min(res, i - cur[1] + 1);
}
if (!map.containsKey(nums[i])) {
map.put(nums[i], cur);
}
}
return res;
}
}