题目描述
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.
这道题给了我们一个数组,定义数组的度为某个或某些数字出现最多的次数,要我们找最短的子数组使其和原数组拥有相同的度。
解题思路
首先要用哈希表来建立每个数字和其出现次数之间的映射,还要建立每个数字和其第一次出现位置之间的映射,那么我们当前遍历的位置其实可以看作是尾位置,还是可以计算子数组的长度的。
我们遍历数组,累加当前数字出现的次数,如果某个数字是第一次出现,建立该数字和当前位置的映射,如果当前数字的出现次数等于degree时,当前位置为尾位置,首位置在startIdx中取的,二者做差加1来更新结果res;如果当前数字的出现次数大于degree,说明之前的结果代表的数字不是出现最多的,直接将结果res更新为当前数字的首尾差加1的长度,然后degree也更新为当前数字出现的次数。
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
int n = nums.size(), res = INT_MAX, degree = 0;
unordered_map<int, int> m, startIdx;
for (int i = 0; i < n; ++i) {
++m[nums[i]];
if (!startIdx.count(nums[i])) startIdx[nums[i]] = i;
if (m[nums[i]] == degree) {
res = min(res, i - startIdx[nums[i]] + 1);
} else if (m[nums[i]] > degree) {
res = i - startIdx[nums[i]] + 1;
degree = m[nums[i]];
}
}
return res;
}
};