Question:

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.

给定非负整数NUMS的非空数组,该数组的程度被定义为其任何元素之一的最大频率。

您的任务是找到与NUM具有相同程度的NUM(相邻)子阵列的最小可能长度。

Example:

  1. Input: [1, 2, 2, 3, 1]
  2. Output: 2
  3. Explanation:
  4. The input array has a degree of 2 because both elements 1 and 2 appear twice.
  5. Of the subarrays that have the same degree:
  6. [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
  7. The shortest length is 2. So return 2.
Input: [1,2,2,3,1,4,2]
Output: 6

Solution:

/**
 * @param {number[]} nums
 * @return {number}
 */
var findShortestSubArray = function(nums) {
    let obj = {}, max = 0, result = nums.length;
    for(let i = 0; i < nums.length; i++) {
        if(!obj[nums[i]]) {
            obj[nums[i]] = [i];
        } else {
            let t = obj[nums[i]];
            t.push(i);
            obj[nums[i]] = t;
        }
    }

    for (let [key, value] of Object.entries(obj)) {
        if(value.length === max) {
            result = Math.min(result, value[value.length - 1] - value[0] + 1);
        }
        if(value.length > max) {
            result = value[value.length - 1] - value[0] + 1;
            max = value.length;
        }
    }

    return result;
};