題目
給定一個非空且只包含非負數的整數數組 nums, 數組的度的定義是指數組裏任一元素出現頻數的最大值。
你的任務是找到與 nums 擁有相同大小的度的最短連續子數組,返回其長度。
示例 1:
輸入: [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:
輸入: [1,2,2,3,1,4,2]
輸出: 6
注意:
nums.length 在1到50,000區間範圍內。
nums[i] 是一個在0到49,999範圍內的整數。
解題思路
使用leetcode 自帶的uthash 構建hash表,再進行排序,
構建時,記錄第一次出現的位置 first, 每次出現,數量增加,同時替換 最後一次出現的位置。
構建完成後,對整個hash 表進行2重排序,先以數量作降序排序,在以長度做升序排序。
最後的長度,就是end-first +1 因爲從0開始計數 需加上。
代碼
struct hash_entry {
int id; /* we'll use this field as the key */
int num;
int first;
int end;
UT_hash_handle hh; /* makes this structure hashable */
};
struct hash_entry *g_head =NULL;
int sort_by_num(struct hash_entry *a,struct hash_entry *b)
{
if(b->num != a->num){
return (b->num - a->num);
}else{
int lena = a->end -a->first;
int lenb = b->end -b->first;
return(lena-lenb);
}
}
void sort()
{
HASH_SORT(g_head,sort_by_num);
}
int findShortestSubArray(int* nums, int numsSize){
int len =0;
//構建hash
for(int i =0;i<numsSize;i++)
{
struct hash_entry *tmp =NULL;
int key =nums[i];
HASH_FIND_INT(g_head,&key,tmp);
if(tmp==NULL)
{
tmp =(struct hash_entry *)malloc(sizeof(struct hash_entry));
tmp->id =key;
tmp->first =i;
tmp->end =i;
tmp->num = 1;
HASH_ADD_INT(g_head,id,tmp);
}
else
{
tmp->end=i;
tmp->num++;
}
}
//排序,查詢
sort();
len = (g_head->end - g_head->first) +1;
//release g_head
struct hash_entry *cur,*tmp2;
HASH_ITER(hh,g_head,cur,tmp2)
{
//printf("val%d %d:start:%d,end%d\n",cur->id,cur->num,cur->first,cur->end);
HASH_DEL(g_head,cur);
free(cur);
}
return len;
}