给定一个非空且只包含非负数的整数数组 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范围内的整数。
C++
class Solution {
public:
int findShortestSubArray(vector<int>& nums)
{
int n=nums.size();
map<int,vector<int>> tmp;
for(int i=0;i<n;i++)
{
tmp[nums[i]].push_back(i);
}
int count=0;
int res=INT_MAX;
map<int,vector<int>>::iterator it;
for(it=tmp.begin();it!=tmp.end();it++)
{
int m=it->second.size();
if(m>count)
{
count=m;
res=it->second[m-1]-it->second[0]+1;
}
if(m==count)
{
res=min(res,it->second[m-1]-it->second[0]+1);
}
}
return res;
}
};
python
class Solution:
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic={}
count=0
n=len(nums)
res=n
for i in range(n):
if nums[i] not in dic:
dic[nums[i]]=[i]
else:
dic[nums[i]].append(i)
for key in dic:
m=len(dic[key])
if m>count:
count=m
res=dic[key][m-1]-dic[key][0]+1
if m==count:
res=min(res,dic[key][m-1]-dic[key][0]+1)
return res