<p>Given a non-empty array of non-negative integers <code>nums</code>, the <b>degree</b> of this array is defined as the maximum frequency of any one of its elements.</p>

<p>Your task is to find the smallest possible length of a (contiguous) subarray of <code>nums</code>, that has the same degree as <code>nums</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,2,3,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> 
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.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,2,3,1,4,2]
<strong>Output:</strong> 6
<strong>Explanation:</strong> 
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>nums.length</code> will be between 1 and 50,000.</li>
	<li><code>nums[i]</code> will be an integer between 0 and 49,999.</li>
</ul>

class Solution {
    struct Counter {
        Counter() : first(-1), last(-1), count(0) {}
        int getDistance() const {
            if (count < 2) return count;
            else return last - first + 1;
        }
        int first, last, count;
    };

public:
    int findShortestSubArray(vector<int>& nums) {
        array<int, 50000> arr{0};
        for (auto i : nums) ++arr[i];

        int degree = 0;
        unordered_set<int> elems;
        for (int i = 0; i < arr.size(); ++i) {
            if (arr[i] > degree) {
                elems.clear();
                elems.insert(i);
                degree = arr[i];
            } else if (arr[i] == degree) {
                elems.insert(i);
            }
        }
        if (degree == 1) return 1;

        int min_distance = INT_MAX;
        for (auto x : elems) {
            int i = 0, j = nums.size() - 1;
            while (i < j) {
                if (nums[i] == nums[j] && nums[i] == x) {
                    min_distance = min(min_distance, j - i + 1);
                    break;
                }
                if (nums[i] != x) ++i;
                if (nums[j] != x) --j;
            }
        }
        return min_distance;
    }
};
37792