版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/85038655
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 asnums
.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
题目:一个array的度degree就是数字出现的最高的频率
求频率相同的subarray的最小长度
-》可以get到的信息:1 要先求degree,且要知道每个数字的degree -》max degree
2 频率相同的subarray一定是包含maxdegree的数字的,所以只针对度为maxdegree的数字去找subarray就好,要求最小长度,说明这个数字作为subarray的开头和结尾
1 slow slow slow method ( 遍历很容易超时
利用了collections.Counter求每个数字出现的频率,返回的是一个字典dict{num:count}
得到max degree和度为maxdegree的数字
遍历得到的数字求min length
class Solution:
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
度相同的最小子列长度
"""
length = len(nums)
if length == 1:return 1
count = collections.Counter(nums)
sortCount = list(count.values())
sortCount.sort()
maxD = sortCount[-1]
degreeList = [key for key,val in count.items() if val == maxD]
revNum = nums.copy()
revNum.reverse()
minL = length
for x in degreeList:
# if nums.count(x) == maxD:
count1 = nums.index(x)
count2 = revNum.index(x)
minL = min(minL,length - count2 - count1)
return minL
Runtime: 756 ms, faster than 8.13% of Python3