您将获得一个整数数组
nums
和一个正整数k
。返回 nums
的最大元素在该子数组中至少出现 k
次的子数组数。
子数组是数组中连续的元素序列。
k maxElement counts
,请继续扩大窗户more than equal to k maxElement counts
,请增加 ans
并努力缩短/滑动窗口class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
i = j = 0
count = 0
ans = 0
N = len(nums)
max_element = max(nums)
while j < N:
# keep increasing the window
if count < k:
count+= nums[j] == max_element
j+=1
# slide/decrease the window
else:
ans+=1
if nums[i] == max_element:
count-=1
i+=1
return ans
可能出现的问题是
ans
变量中。nums = [1,3,2,3,3]
和 K 当前子数组是 [3,2,3]
我已经满足了 count >= k
所以我不会考虑 [3,2,3,3]
我会致力于缩短子数组。nums=[1,3,2,3,3] and k = 2 Output = 2 Expected Output = 6
处失败,两个子数组为 [1, 3, 2, 3] and [3, 2, 3]
问题出在
else
子句中,您只需增加结果即可。但实际上所有从 i
开始、结束索引为 >= j
的子数组都满足条件。因此,您必须做 ans += 1
,而不是 ans += N - j
。除此之外,你的算法看起来不错。