Description:
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:
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:
Note:
nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999.
题意:给定一个非空且元素非负的一维数组,定义数组的最大频率为元素重复出现的最大次数;现要求找出数组的一个子数组满足其最大频率和原数组相同,并且要求找到的子数组长度最短;
解法:如果[num]为数组中出现次数最多的元素,假设出现次数为[t],那么所找的符合要求的子数组中[num]出现的次数也应当为[t];那么我们可以为每个元素标记他从数组首部开始最早出现的下标位置[leftIndex]和从数组尾部开始最早出现的下标位置[rightIndex],由这两个位置构成的数组的长度为[rightIndex - leftIndex + 1];