给定一个非空且只包含非负数的整数数组 n u m s nums nums,数组的度的定义是指数组里任一元素出现频数的最大值。
你的任务是在 n u m s nums nums 中找到与 n u m s 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
提示:
n u m s . l e n g t h 在 1 到 50 , 000 区 间 范 围 内 。 n u m s [ i ] 是 一 个 在 0 到 49 , 999 范 围 内 的 整 数 。 nums.length 在1到 50,000 区间范围内。\\ nums[i] 是一个在 0 到 49,999 范围内的整数。 nums.length在1到50,000区间范围内。nums[i]是一个在0到49,999范围内的整数。
class Solution {
public:
int findShortestSubArray(vector<int> &nums) {
map<int, vector<int>> ma;
int n = nums.size();
for (int i = 0; i < n; i++) {
if (ma.count(nums[i])) {
ma[nums[i]][0]++;
ma[nums[i]][2] = i;
} else {
ma[nums[i]] = {1, i, i};
}
}
int mx = 0;
int ans = 0;
for (auto &[x, y]:ma) {
if (y[0] > mx) {
ans = y[2] - y[1] + 1;
mx = y[0];
} else {
if (y[0] == mx) {
ans = min(ans, y[2] - y[1] + 1);
}
}
}
return ans;
}
};