697. 数组的度

 

 

 

思路:

1、nums转set去重,为newlist;
2、遍历newlist找出最大频数maxnum;
3、遍历newlist针对满足最大频数的元素ch,求其代表的连续子数组:
a) 从左往右遍历,找到第一个ch的下标low;
b) 从右往左遍历,找到第一个ch的下标high;
将该子数组长度:high-low+1保存在res[ ]中;
4、返回min(res)。
 1 class Solution(object):
 2     def findShortestSubArray(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         # 去重
 8         newlist = list(set(nums))
 9         # 记录最大频数
10         maxnum = 0
11         # 返回min(res)
12         res = []
13         # 找出maxnum
14         for ch in newlist:
15             if nums.count(ch) > maxnum:
16                 maxnum = nums.count(ch)
17         for ch in newlist:
18             # 满足最大频数的元素
19             if nums.count(ch) == maxnum:
20                 # 求相同度的子数组的长度
21                 low = nums.index(ch)
22                 high = -1
23                 for i in range(len(nums) - 1, -1, -1):
24                     if nums[i] == ch:
25                         high = i
26                         break
27                 res.append(high - low + 1)
28         return min(res)
29 
30 
31 if __name__ == '__main__':
32     solution = Solution()
33     print(solution.findShortestSubArray([1, 2, 2, 3, 1]))
 
原文地址:https://www.cnblogs.com/panweiwei/p/12800009.html