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.
意思:首先定义了一个数组的度,就是最大频度的那个元素的个数。我们需要找到一个数组的度的最小子串。
https://leetcode.com/contest/leetcode-weekly-contest-54/problems/degree-of-an-array/
这里有几个概念需要理解清晰,才能设计算法。
1. 数组的度,最大的那个元素的个数。(看起来很容易理解。)
2. 数组的子数组,也就是类似字符串的substring。(看起来很容易理解)
3. 数组同度的子数组,可能很多个,至少有一个,就是自身。
4. 找到一个最小长度的子数组。
5. 最小长度的子数组怎么找到呢?满足度的,起始位置之差则是长度。
6. 长度最小即为答案。
分析了上面这些,应该问题差不多可以有眉目了。
http://blog.csdn.net/neverever01/article/details/78257600
http://blog.csdn.net/u011809767/article/details/78248289
public int findShortestSubArray(int[] nums) {
//transfer one time , we can find the shortest subarray?
int fre[] = new int[50000]; //each nums fre
int pos[] = new int[50000]; //each num first pos!
int maxDegree = -1;
int minLength = 50000;
for(int i=0;ilength;i++)
{
int val = nums[i];
fre[val]++;
if(fre[val]==1)
{
pos[val] = i; //begin for this val
}
if(fre[val]>=maxDegree)
{
int temp = i-pos[val]+1;
if(fre[val]>maxDegree)
minLength = temp;
else
if(temp// System.out.println(val+",degree:"+fre[val]+",begin:"+pos[val]+",end:"+i+",minlength:"+minLength);
}
}
return minLength;
}