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(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
first, counter, res, degree = {}, {}, 0, 0
for i, v in enumerate(nums):
first.setdefault(v, i)
counter[v] = counter.get(v, 0)+1
if counter[v]>degree:
degree = counter[v]
res = i-first[v]+1
elif counter[v]==degree:
res = min(res, i-first[v]+1)
return res
1 首先得到array的degree,调用collections.Counter().most_common(1)
2 怎么有效地去遍历各个subarray
3 因为涉及到index和value,所以用enumerate
4 设置两个dictionary,第一个first记录v第一次出现的index,counter记录出现的次数
5 依次遍历array,得到每一个字符的first index和count,同时记录返回长度
6 当遍历到后面,degree是一样的时候,需要返回最小的长度
7 first.setdefault(v, i) 如果v在dict中,就直接返回初始index就行,如果不在dict中,把当前的index写进去
8 counter[v] = counter.get(v, 0)+1, 这和first不同在于,counter是需要每次加1的,所以此处不用first.setdefault(v, i),只是每次在get到的值的基础上加1,初始化为0