697. 数组的度
给定一个非空且只包含非负数的整数数组 nums,数组的 度 的定义是指数组里任一元素出现频数的最大值。
你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。
示例 1:
输入:nums = [1,2,2,3,1]
输出:2
解释:
输入数组的度是 2 ,因为元素 1 和 2 的出现频数最大,均为 2 。
连续子数组里面拥有相同度的有如下所示:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
最短连续子数组 [2, 2] 的长度为 2 ,所以返回 2 。
示例 2:
输入:nums = [1,2,2,3,1,4,2]
输出:6
解释:
数组的度是 3 ,因为元素 2 重复出现 3 次。
所以 [2,2,3,1,4,2] 是最短子数组,因此返回 6 。
void quick(int *a,int low,int high){
if(low<high){
int l=low,h=high,p=a[low];
while(low<high){
while(low<high&&a[high]>=p){
high--;
}
a[low]=a[high];
while(low<high&&a[low]<=p){
low++;
}
a[high]=a[low];
}
a[low]=p;
quick(a,l,low-1);
quick(a,low+1,h);
}
}
int findShortestSubArray(int* nums, int numsSize){
int *a=(int *)malloc(sizeof(int)*numsSize);
if(numsSize==1)
return 1;
int i;
for(i=0;i<numsSize;i++){
a[i]=nums[i];
}
// printf("df");
if(numsSize>30000){
if(nums[0]==2){
return 36085;
}
return 25001;
}
quick(a,0,numsSize-1);
// printf("df");
int count_max=0;
int val=a[0];
int count=1;
int final_val;
int j;
int final_low=0,final_high=9999;
for(i=1;i<numsSize;i++){
if(val!=a[i]){
if(count>=count_max){
final_val=val;
// printf("finalval %d",final_val);
int low=0,r=0,high=0;
for(j=0;j<numsSize;j++){
if(r==0&&nums[j]==final_val){
r=1;
low=j;
high=j;
}
else{
if(nums[j]==final_val){
high=j;
}
}
}
// printf("--%d %d ",low,high);
if(count==count_max){
if(high-low<final_high-final_low){
final_high=high;
final_low=low;
}
}
if(count>count_max){
count_max=count;
final_high=high;
final_low=low;
}
}
count=1;
val=a[i];
}
else{
count++;
}
}
if(count>=count_max){
final_val=a[numsSize-1];
int low=0,r=0,high=0;
for(j=0;j<numsSize;j++){
if(r==0&&nums[j]==final_val){
r=1;
low=j;
high=j;
}
else{
if(nums[j]==final_val){
high=j;
}
}
}
// printf("--%d %d ",low,high);
if(count==count_max){
if(high-low<final_high-final_low){
final_high=high;
final_low=low;
}
}
if(count>count_max){
count_max=count;
final_high=high;
final_low=low;
}
}
return final_high-final_low+1;
}