697. Degree of an Array
Easy
457375FavoriteShare
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.
看到这道题是easy才做的,调了半天终于AC了。这也叫easy啊!
调的地方有一些特殊测试例子失败:[1],[1,1],还有个很恶心答案501的超长case,我写个类似的[1,1,1,2,2,2,2]
要注意的地方就是在数数的时候,当j增大到越界时一定要检查,如果还没有maxnn.size(),比如[1],[1,1]这样的测试用例,一定要加上,还要检查现在的数量是否已经是max了。
解题思路是:1.先数出出现最多的数字和个数,2.如果有多个出现次数最多的数字,分别计算包含它们的长度,用两个指针分别从两头往里移动,计算最小长度。
代码如下:
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
if(nums.size()==1)return 1;
vector<int> temp=nums;
sort(temp.begin(),temp.end());
int i=0;
int j=0;
int now=0;//记录当前数字的个数
int maxn=0;//记录出现的最多的数字的个数
vector<int> maxnn;//因为可能出现很多数字的个数都是一样的,所以用一个数组来记录这些数字
//先数出出现最多的数字和个数
while(j<temp.size())
{
if(temp[i]==temp[j])
{
now++;
j++;
//if(!maxnn.size())maxnn.push_back(temp[i]);
}
else
{
if(now>maxn)
{
maxn=now;
maxnn.clear();
maxnn.push_back(temp[i]);
}
else if(now==maxn)
{
maxnn.push_back(temp[i]);
}
now=0;
i=j;
}
if (j == temp.size())
{
if (!maxnn.size())maxnn.push_back(temp[i]);
if(now>maxn)
{
maxn=now;
maxnn.clear();
maxnn.push_back(temp[i]);
}
else if(now == maxn)
{
maxnn.push_back(temp[i]);
}
}
}
//如果有多个出现次数最多的数字,分别计算包含它们的长度,用两个指针分别从两头往里移动,计算最小长度。
int minL=0;//最小长度
int p=maxnn.size()-1;
int ans=0x7fffffff;
while(p>=0)
{
i=0;
j=nums.size()-1;
int a=maxnn[p];
while(nums[i]!=a)i++;
while(nums[j]!=a)j--;
ans=min(ans,j-i+1);
p--;
}
return ans;
}
};