697. Degree of an Array

创建两个字典,保存index
first, last = {}, {}
用这两个字典保存每个字符最先出现和最后出现的位置

for i, v in enumerate(nums):
            first.setdefault(v, i)
            last[v] = i

再找出数组最多出现元素出现的次数
c = collections.Counter(nums)
degree = max(c.values())
最后返回最短长度
return min(last[v] - first[v] + 1 for v in c if c[v] == degree)

你可能感兴趣的:(697. Degree of an Array)