# 697.Degree of an Array

697.Degree of an Array

[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]

nums.length 在1到50,000区间范围内。
nums[i] 是一个在0到49,999范围内的整数。

class Solution {
int len(vector<int >nums, int index, int degree)
{
int start=index+1;
int count=1;
while(count<degree)
{
if(nums[start]==nums[index])
{
++count;
}
++start;
}
return start-index ;
}
public:
int findShortestSubArray(vector<int>& nums) {
unordered_map<int,int>degree_of_nums;
int max_index=nums[0];
for(auto n:nums)
{
degree_of_nums[n]++;
if(degree_of_nums[max_index]<degree_of_nums[n])
max_index=n;
}
int degree=degree_of_nums[max_index];
max_index=find(nums.begin(),nums.end(), max_index) - nums.begin();
//cout<<max_index<< "--" << degree_of_nums[nums[max_index]] <<endl;
int res=len(nums, max_index, degree_of_nums[nums[max_index]]);
for(auto &e: degree_of_nums)
{
if(e.first != nums[max_index] && e.second == degree)
res = min(res, len(nums, find(nums.begin(), nums.end(), e.first)-nums.begin(), degree));
}
return res;
}
};