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.

数组的度。

给定一个非空且只包含非负数的整数数组 nums,数组的度的定义是指数组里任一元素出现频数的最大值。

你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。

 

思路是用两个hashmap,一个记录数字的出现次数,一个记录每个不同数字最早出现的坐标。当每次发现一个出现次数最多的数字的时候,就更新子数组的长度;如果发现有多个数字的出现次数都是最多的情况下,则查看是否能缩小子数组的长度。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int findShortestSubArray(int[] nums) {
 3         Map<Integer, Integer> count = new HashMap<>();
 4         Map<Integer, Integer> first = new HashMap<>();
 5         int res = 0;
 6         int degree = 0;
 7         for (int i = 0; i < nums.length; i++) {
 8             first.putIfAbsent(nums[i], i);
 9             count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
10             if (count.get(nums[i]) > degree) {
11                 degree = count.get(nums[i]);
12                 res = i - first.get(nums[i]) + 1;
13             } else if (count.get(nums[i]) == degree) {
14                 res = Math.min(res, i - first.get(nums[i]) + 1);
15             }
16         }
17         return res;
18     }
19 }

 

LeetCode 题目总结