难度:easy
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
思路: 题目讲得不清不楚,花了些功夫才搞懂。找到所给list里面重复次数最多的那个数的重复次数,即为该list的degree。然后寻找与原list的degree相同的最短子list。也就是重复出现次数最多的那个数在原list中出现的位置的从最左到最右之间的片段。
用enumerate() 遍历list,同时获取索引和对应的值,设计三个dictionary,left 用于存放每个element在list中第一次出现的索引,right用于存放每个element在list中最后出现的索引。count用于存放每个element出现的次数。
最后遍历count,找到所有value=degree的key,取最小值。