Degree of an Array

2017/11/23 posted in  leetcode

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.

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        
        if (nums.size()<2) {
            return nums.size();
        }
        unordered_map<int, int>startIndex , number;
        int len = nums.size();
        int fre = 0;
        for (int i=0; i<nums.size(); i++) {
            if (startIndex.count(nums[i])==0) {
                startIndex[nums[i]]=i;
            }
            number[nums[i]]++;
            if (number[nums[i]]==fre) {
                len = min(i-startIndex[nums[i]]+1, len);
            }
            if (number[nums[i]]>fre) {
                len = i - startIndex[nums[i]] + 1;
                fre = number[nums[i]];
            }
        }
        
        return len;
    }
};

该算法主要使用了两个hash_map:
一个来记录数字所出现的次数,另一个记录数字最开始出现的位置。一旦有一个数字的频数超过了当前的len,则更新len,若两个数字出现的频率相等则取长度最小的。