Leetcode Link: 697. 数组的度 - 力扣(LeetCode)

题目

解法一

思路

  1. 求度
  2. 找出现次数== 度的数字
  3. 找到这些数字的位置
  4. 找到最短的

题解

class Solution:
    def findShortestSubArray(self, nums: List[int]) -> int:
        # 求度
        degree = max(list(Counter(nums).values()))
        # 特例
        if degree == 1: return 1
        # 找所有出现次数==度的数,即所有的众数
        dd = Counter(nums)
        candi = []
        for k, v in dd.items():
            if v == degree:
                candi.append(k)
        # res和candi一一对应,每个元素保存对应数字出现的位置
        # e.g. res = [[1,2,3], [4,6,9]],其元素表示两个数字出现的所有位置
        res = [[] for _ in range(len(candi))] 
        for i, val in enumerate(nums):
            if val in candi:
                res[candi.index(val)].append(i)
        
        return min([x[-1]-x[0]+1 for x in res])