Leetcode之Degree of an Array

Topic description

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. This
question gives us an array, defines the degree of the array as the number of times a certain number or numbers appear the most, and asks us to find the shortest subarray that has the same degree as the original array.

Problem solving ideas

First, a hash table is used to establish a mapping between each number and its number of occurrences, and a mapping between each number and its first occurrence position, then the position we currently traverse can actually be regarded as the tail position, and the length of the subarray can still be calculated.
We traverse the array and accumulate the number of occurrences of the current number. If a number appears for the first time, establish a mapping between the number and the current position. If the number of occurrences of the current number is equal to degree, the current position is the tail position and the first position is startIdx Take the difference between the two and add 1 to update the result res; if the number of occurrences of the current number is greater than degree, it means that the number represented by the previous result does not appear the most, and directly update the result res to the difference between the beginning and the end of the current number plus 1 length, then degree is also updated to the current number of occurrences of the number.

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        int n = nums.size(), res = INT_MAX, degree = 0;
        unordered_map<int, int> m, startIdx;
        for (int i = 0; i < n; ++i) {
            ++m[nums[i]];
            if (!startIdx.count(nums[i])) startIdx[nums[i]] = i;
            if (m[nums[i]] == degree) { 
                res = min(res, i - startIdx[nums[i]] + 1);
            } else if (m[nums[i]] > degree) {
                res = i - startIdx[nums[i]] + 1;
                degree = m[nums[i]];
            }
        }
        return res;
    }
};

Guess you like

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