您的位置:首页 > 科技 > IT业 > chatgpt网址_电商设计师和美工有什么区别_推广方式有哪几种_seo有哪些优缺点?

chatgpt网址_电商设计师和美工有什么区别_推广方式有哪几种_seo有哪些优缺点?

2025/5/1 7:35:38 来源:https://blog.csdn.net/Tisfy/article/details/147620212  浏览:    关键词:chatgpt网址_电商设计师和美工有什么区别_推广方式有哪几种_seo有哪些优缺点?
chatgpt网址_电商设计师和美工有什么区别_推广方式有哪几种_seo有哪些优缺点?

【LetMeFly】2962.统计最大元素出现至少 K 次的子数组:滑动窗口

力扣题目链接:https://leetcode.cn/problems/count-subarrays-where-max-element-appears-at-least-k-times/

给你一个整数数组 nums 和一个 正整数 k

请你统计有多少满足 「 nums 中的 最大 元素」至少出现 k 次的子数组,并返回满足这一条件的子数组的数目。

子数组是数组中的一个连续元素序列。

 

示例 1:

输入:nums = [1,3,2,3,3], k = 2
输出:6
解释:包含元素 3 至少 2 次的子数组为:[1,3,2,3]、[1,3,2,3,3]、[3,2,3]、[3,2,3,3]、[2,3,3] 和 [3,3] 。

示例 2:

输入:nums = [1,4,2,1], k = 3
输出:0
解释:没有子数组包含元素 4 至少 3 次。

 

提示:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 106
  • 1 <= k <= 105

解题方法:滑动窗口

首先遍历一遍数组得到数组中最大的元素。

之后使用两个指针分别指向窗口中的第一个和最后一个元素的下标,不断右移右指针,并将新元素加入窗口。

当窗口中“最大数个数”等于k时,不断右移左窗口并将左边元素移出窗口。此时左指针左边(不含左指针)的任何一个元素开始到右指针所组成的子数组都合法。

  • 时间复杂度 O ( l e n ( n u m s ) ) O(len(nums)) O(len(nums))
  • 空间复杂度 O ( 1 ) O(1) O(1)

AC代码

C++
/** @Author: LetMeFly* @Date: 2025-04-29 13:19:27* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-04-29 21:19:24*/
typedef long long ll;class Solution {
public:long long countSubarrays(vector<int>& nums, int k) {int mx = nums[0];for (int t : nums) {mx = max(mx, t);}ll ans = 0;for (int l = 0, r = 0, cnt = 0; r < nums.size(); r++) {cnt += nums[r] == mx;while (cnt == k) {cnt -= nums[l++] == mx;}ans += l;}return ans;}
};
Python
'''
Author: LetMeFly
Date: 2025-04-29 13:19:47
LastEditors: LetMeFly.xyz
LastEditTime: 2025-04-29 21:21:03
'''
from typing import Listclass Solution:def countSubarrays(self, nums: List[int], k: int) -> int:mx = max(nums)l = cnt = ans = 0for t in nums:cnt += t == mxwhile cnt == k:cnt -= nums[l] == mxl += 1ans += lreturn ans
Java
/** @Author: LetMeFly* @Date: 2025-04-29 13:19:49* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-04-29 21:23:01*/
class Solution {public long countSubarrays(int[] nums, int k) {int mx = nums[0];for (int t : nums) {mx = Math.max(mx, t);}long ans = 0;for (int l = 0, cnt = 0, r = 0; r < nums.length; r++) {if (nums[r] == mx) {cnt++;}while (cnt == k) {if (nums[l++] == mx) {cnt--;}}ans += l;}return ans;}
}
Go
/** @Author: LetMeFly* @Date: 2025-04-29 13:20:02* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-04-29 13:23:23*/
package mainfunc countSubarrays(nums []int, k int) (ans int64) {M := nums[0]for _, t := range nums {M = max(M, t)}for l, r, cnt := 0, 0, 0; r < len(nums); r++ {if nums[r] == M {cnt++}for cnt >= k {if nums[l] == M {cnt -= 1}l++}ans += int64(l)}return
}

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

千篇源码题解已开源

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com