题目描述:
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.
Example 1:
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
Example 2:
Input: [1,2,2,3,1,4,2]
Output: 6
Note:
nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999.
一个数组的度的定义是频率最高元素出现的次数。求一个数组中最短的,度和原数组相同的子数组。为了求出数组的度,需要统计每个元素的次数,同时记录每个元素出现的第一个下标和最后一个下标,这样在遍历数组的过程中可以同时更新元素次数,一旦发现频率最高的元素,可以更新子数组的长度。
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
unordered_map<int,int> count;
unordered_map<int,int> first_index;
unordered_map<int,int> last_index;
int max_count=0;
int min_length=INT_MAX;
for(int i=0;i<nums.size();i++)
{
if(first_index.count(nums[i])==0) first_index[nums[i]]=i;
last_index[nums[i]]=i;
count[nums[i]]++;
if(count[nums[i]]==max_count)
min_length=min(min_length,last_index[nums[i]]-first_index[nums[i]]+1);
else if(count[nums[i]]>max_count)
{
max_count=count[nums[i]];
min_length=last_index[nums[i]]-first_index[nums[i]]+1;
}
}
return min_length;
}
};
本文介绍了一种高效算法,用于找到一个数组中度(即任意元素最大出现次数)与原数组相等的最短子数组。通过使用三个哈希映射,分别记录元素的计数、首次出现位置和最后出现位置,算法能在一次遍历中完成任务。
416

被折叠的 条评论
为什么被折叠?



