Count Subarrays With Median K
Count Subarrays With Median K
You are given an array nums of size consisting of distinct integers from to and a positive integer .
Return the number of non-empty subarrays in nums that have a median equal to .
Note:
- The median of an array is the middle element after sorting the array in ascending order. If the array is of even length, the median is the left middle element.
- For example, the median of is , and the median of is .
- A subarray is a contiguous part of an array.
Example 1:
Input: nums = [3,2,1,4,5], k = 4 Output: 3 Explanation: The subarrays that have a median equal to 4 are: [4], [4,5] and [1,4,5].
Example 2:
Input: nums = [2,3,1], k = 3 Output: 1 Explanation: [3] is the only subarray that has a median equal to 3.
Constraints:
- The integers in nums are distinct.
解题思路
没做出来,菜。
关键是要想到下面这个性质,如果一个长度为的数组排序后的中位数是,如果是奇数,那么大于的数的个数应该恰好为,小于的数的个数也恰好为;如果是偶数,那么大于的数的个数应该恰好为, 小于的数的个数应该恰好为。
接着我们可以构造一个数组,如果,那么;如果,那么;如果,那么。任然后对数组求前缀和,得到前缀和数组。如果某个区间排序后的中位数为,问题就变成了,如果区间长度为奇数那么;如果区间长度为偶数那么。
因此我们可以枚举区间右端点,根据的奇偶性看看有多少个 ()满足上面的条件,因此可以开个哈希表,每次枚举完后根据的奇偶性来统计(代码是枚举之前统计)。
这里有个坑要注意的是由于区间的中位数必须要包含这个数,假设在原数组中的下标为,因此在用哈希表统计的时候应该统计必定包含的,也就是说当的时候就不能再用哈希表记录了。
AC代码如下:
1 class Solution { 2 public: 3 int countSubarrays(vector<int>& nums, int k) { 4 int n = nums.size(); 5 vector<int> s(n + 1); 6 int x; 7 for (int i = 1; i <= n; i++) { 8 if (nums[i - 1] == k) x = i; 9 int t = 0; 10 if (nums[i - 1] > k) t = 1; 11 else if (nums[i - 1] < k) t = -1; 12 s[i] = s[i - 1] + t; 13 } 14 unordered_map<int, int> mp[2]; 15 int ret = 0; 16 for (int i = 1; i <= n; i++) { 17 if (i - 1 < x) mp[i - 1 & 1][s[i - 1]]++; // 当j - 1 >= x,区间[i, j]就不包含k了 18 ret += mp[i & 1][s[i] - 1] + mp[i - 1 & 1][s[i]]; // 区间长度为偶数的情况加上区间长度为奇数的情况 19 } 20 return ret; 21 } 22 };
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/16929578.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效