697. 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

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

读题不懂

[一句话思路]:

先统计,再比较

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 数字一般初始化为整数中相反的最大或者最小值,忘了
  2. 忘了 检查key用的是containsKey方法

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

有很多指标,所以用多维数组+hashmap来实现

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

  1. 某数字 最大值的 最小覆盖范围, 有很多指标,所以用多维数组+hashmap来实现
  2. hashmap可以用for(: .values())冒号表达式把所有值取出来

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

put中直接写数值 不能再赋值,所以new int[]{直接跟数组即可}

class Solution {
    public int findShortestSubArray(int[] nums) {
        //cc
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        //ini
        HashMap<Integer, int[]> map = new HashMap<>();
        
        //collect into hashmap
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], new int[]{1, i, i});//val, first index, last index
            }else {
                int temp[] = map.get(nums[i]);
                temp[0] += 1;
                temp[2] = i;
                map.put(nums[i], temp);
            }
        }
        
        //compare
        //bigger degree
        //same degree but smaller range
        //ini to the extreme
        int degree = Integer.MIN_VALUE;
        int result = Integer.MAX_VALUE;
        
        for (int[] val : map.values()) {
            if (val[0] > degree) {
                degree = val[0];
                result = val[2] - val[1] + 1;
            }else {
                if (val[0] == degree) {
                    result = Math.min(result,  val[2] - val[1] + 1);
                }
            }
        }
        
        //return
        return result;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/8875741.html