LeetCode刷题——Array篇(Degree of an Array)

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.

Example 1:
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
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.
Example 2:
Input: [1,2,2,3,1,4,2]
Output: 6
Note:

nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999.

1. Since I want to hash quickly, I want to use a hash table at first, but only one, and also need to find the maximum and minimum subscripts of the numbers with the most occurrences;
2. Therefore, use the area for the speed Three hash tables, one to record the number of occurrences, one to record the minimum subscript, and one to record the maximum subscript

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        int count = nums.size();
        unordered_map<int, int> map;
        unordered_map<int, int> min;
        unordered_map<int, int> max;

        int max_degree = 1;
        for (int i = 0; i < count; i++)
        {
            unordered_map<int, int>::iterator map_it = map.find(nums[i]);
            if (map_it == map.end())
            {
                //cout << "不存在" << endl;
                map.insert(make_pair(nums[i], 1));
                min.insert(make_pair(nums[i], i));
                max.insert(make_pair(nums[i], i));
            }
            else
            { 
                (map_it->second)++;
                max[nums[i]] = i;
                //cout<< map_it->first<<":" << map_it->second << endl;
                if ((map_it->second) > max_degree)
                {
                    max_degree = map_it->second;
                }
            }
        }
        //cout << max_degree << endl;
        int degree = 0;
        for (unordered_map<int, int>::iterator it = map.begin(); it != map.end(); it++)
        {
            if (it->second == max_degree)
            {
                int temp = max[it->first] - min[it->first]+1;
                if (temp < degree||degree==0)
                    degree = temp;
            }
        }

        //cout << degree << endl;
        return degree;

    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326041453&siteId=291194637