📅  最后修改于: 2023-12-03 15:26:27.598000             🧑  作者: Mango
给定一个整数数组,找到一个长度最小的子数组,其元素的出现次数严格大于数组中其他元素的出现次数。
[1,2,2,3,3,3,4,4,4,4]
[3,3,3]
from collections import Counter
from typing import List
def find_min_subarr(nums: List[int]) -> List[int]:
counter = Counter(nums)
most_common_element, most_common_count = counter.most_common(1)[0]
min_subarr = []
for i in range(len(nums)):
if nums[i] == most_common_element:
for j in range(i, len(nums)):
subarr = nums[i:j+1]
subarr_counter = Counter(subarr)
if subarr_counter[most_common_element] > sum(subarr_counter.values()) - subarr_counter[most_common_element]:
if not min_subarr or len(subarr) < len(min_subarr):
min_subarr = subarr
return min_subarr
该算法时间复杂度为 $O(n^3)$。在最坏情况下,需要遍历每个子数组,计算每个子数组中元素的出现次数。在实际应用中,可以对第 3 步进行优化,将时间复杂度降至 $O(n^2)$ 或 $O(n)$。