[leetcode]697. Degree of an Array
Analysis
一个有台风的周末~—— [中午吃什么外卖呢~]
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Implement
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
unordered_map<int, int> has, index;
int res = INT_MAX;
int degree = 0;
int len = nums.size();
for(int i=0; i<len; i++){
if(!has.count(nums[i]))
index[nums[i]] = i;
has[nums[i]]++;
if(has[nums[i]] == degree)
res = min(res, i-index[nums[i]]+1);
else if(has[nums[i]] > degree){
degree = has[nums[i]];
res = i - index[nums[i]] + 1;
}
}
return res;
}
};