链接:https://leetcode-cn.com/problems/degree-of-an-array/description/
Q:
给定一个非空且只包含非负数的整数数组 nums
, 数组的度的定义是指数组里任一元素出现频数的最大值。
你的任务是找到与 nums
拥有相同大小的度的最短连续子数组,返回其长度。
示例 1:
输入: [1, 2, 2, 3, 1] 输出: 2 解释: 输入数组的度是2,因为元素1和2的出现频数最大,均为2. 连续子数组里面拥有相同度的有如下所示: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] 最短连续子数组[2, 2]的长度为2,所以返回2.
思路:这个是很久前写的 当时怎么都不能通过 然后今天试了一下莫名其妙的就通过了,思路大概是首先建立字典,因为字典的查询效率高,通过字典统计词频,Counter()有同样的效果,然后统计词频最高的,计算距离,得出距离最小的值,实际上是暴力求解的感觉
class Solution:
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxs = 0
dict_ ={}
temp = []
for ele in nums:
if ele in dict_:
dict_[ele]+=1
else:
dict_[ele] = 1
for i in dict_:
if dict_[i]>maxs:
maxs = dict_[i]
if maxs == 1:
return 1
for j in dict_:
if dict_[j] == maxs:
temp.append(j)
res = []
for t in temp:
start = nums.index(t)
end = 0
for i in range(len(nums)):
if t == nums[i]:
end = i
res.append(end-start)
return min(res)+1