📅  最后修改于: 2023-12-03 15:09:59.193000             🧑  作者: Mango
给定一个整数数组,找到包含相同元素的最大子数组,并返回子数组的起始和结束下标。如果存在多个子数组,则返回任意一个即可。
此问题可以转换为“寻找一组连续的数字,并且这些数字出现的次数相同。”
可以用哈希表来存储每个数字出现的次数,然后遍历数组,记录当前最大子数组的起始和结束下标。
def find_max_subarray(nums):
freq = {}
max_len = 0
start = end = 0
cur_start = 0
for i, num in enumerate(nums):
freq[num] = freq.get(num, 0) + 1
if freq[num] * (i - cur_start + 1) > max_len:
start, end = cur_start, i
max_len = freq[num] * (i - cur_start + 1)
elif freq[num] * (i - cur_start + 1) == max_len:
if i - cur_start > end - start:
start, end = cur_start, i
if i + 1 < len(nums) and nums[i+1] != num:
cur_start = i + 1
return start, end
def test_find_max_subarray():
nums = [1, 2, 3, 4, 5, 6]
assert find_max_subarray(nums) == (0, 0)
nums = [1, 1, 2, 2, 3, 3]
assert find_max_subarray(nums) == (0, 5)
nums = [1, 1, 2, 2, 2, 3, 3]
assert find_max_subarray(nums) == (2, 4)
nums = [1]
assert find_max_subarray(nums) == (0, 0)
nums = []
assert find_max_subarray(nums) == (0, -1)
test_find_max_subarray()
注:该算法时间复杂度为 $O(n)$。