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、既然要快就上hash,因此一开始想使用一个哈希表,但是只用一个,还需要找出现次数最多的几个数的最大、最小下标;
2、所以以面积换速度,使用三个哈希表,一个记录出现次数,一个记录最小下标,一个记录最大下标

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;

    }
};

猜你喜欢

转载自blog.csdn.net/lpcarl/article/details/79989331