📅  最后修改于: 2023-12-03 14:53:48.257000             🧑  作者: Mango
给定一个整数数组 nums,你需要找到一个最长的连续子数组,其中包含相同的元素。
def findLengthOfShortestSubarray(nums: List[int], k: int) -> int:
n = len(nums)
mapping = {}
for i in range(n):
if nums[i] not in mapping:
mapping[nums[i]] = []
mapping[nums[i]].append(i)
distances = []
for positions in mapping.values():
for i in range(1, len(positions)):
distances.append(positions[i] - positions[i-1])
distances.sort()
maxLen = 1
for i in range(len(distances)):
total = sum(distances[i:])
if len(distances)-i <= k:
maxLen = max(maxLen, total)
return n - maxLen
以 nums = [1,2,3,4,5,3,2,1] 和 k = 2 为例,调用函数 findLengthOfShortestSubarray(nums, k) 返回 2,即将原数组最多划分成 2 段:[1,2,3,4,5] 和 [3,2,1] 中包含相同的元素。