# 697.Degree of an Array

**697.Degree of an Array**

难度:Easy

> 给定一个非空且只包含非负数的整数数组 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范围内的整数。
```

创建一个Hash表，然后找出频次最多的元素，找到元素的起始索引，然后找出所有频次最多元素的保留度的最短长度，求出其最小值。

```
class Solution {
int len(vector<int >nums, int index, int degree)
{
    int start=index+1;
    int count=1;
    while(count<degree)
    {
        if(nums[start]==nums[index])
        {
            ++count;

        }
        ++start;
    }
    return start-index ;
}
public:
    int findShortestSubArray(vector<int>& nums) {
        unordered_map<int,int>degree_of_nums;
        int max_index=nums[0];
        for(auto n:nums)
        {
            degree_of_nums[n]++;
            if(degree_of_nums[max_index]<degree_of_nums[n])
                max_index=n;

    }
        int degree=degree_of_nums[max_index];
        max_index=find(nums.begin(),nums.end(), max_index) - nums.begin();

        //cout<<max_index<< "--" << degree_of_nums[nums[max_index]] <<endl;
    int res=len(nums, max_index, degree_of_nums[nums[max_index]]);
        for(auto &e: degree_of_nums)
        {
            if(e.first != nums[max_index] && e.second == degree)
                res = min(res, len(nums, find(nums.begin(), nums.end(), e.first)-nums.begin(), degree));
        }
        return res;
    }
};
```

> 执行用时 :348 ms, 在所有 C++ 提交中击败了5.49%的用户\
> 内存消耗 :284MB, 在所有 C++ 提交中击败了5.62%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/697.degree_of_an_array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
