Leetcode: 2488. Count Subarrays With Median K 统计中位数为 K 的子数组

该算法解决的问题是在一个整数数组中,找出中位数为给定值k的非空子数组的数量。通过使用前缀和和哈希表,计算每个元素后更新前缀和,并统计满足条件的子数组。对于每个元素,更新前缀和,然后检查当前前缀和或前缀和减一是否在哈希表中,若存在则增加计数。
摘要由CSDN通过智能技术生成

You are given an array nums of size n consisting of distinct integers from 1 to n and a positive integer k.

Return the number of non-empty subarrays in nums that have a median equal to k.

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 [2,3,1,4] is 2, and the median of [8,4,3,5,1] is 4.
A subarray is a contiguous part of an array.

思路:(前缀和 + 哈希表)

1、用哈希表存放前缀和对应出现的次数  由于 为偶数时中位数是左边那个 说明 左边可以少一个比k大的数

2、先遍历统计 k前面的数的前缀和出现的次数   大于k为1  小于k为-1

3、遍历剩下的数  计算前缀和  等于k为0   大于k为1   小于k为-1   如果在map中找到presum 或者 presum - 1 说明存在map[presum] / map[presum - 1]个满足条件的数组  用cnt进行计数

代码:

class Solution {
public:
    int countSubarrays(vector<int>& nums, int k) {
        unordered_map<int, int> mymp;
        mymp[0] = 1;
        int cnt = 0, presum = 0;
        int i = 0;
        for(i = 0; nums[i] != k; i++) {
            presum += nums[i] < k? -1: 1;
            mymp[presum]++;
        }
        for(; i < nums.size(); i++) {
            presum += nums[i] < k? -1:(nums[i] == k? 0 : 1);
            if(mymp.find(presum) != mymp.end()) {
                cnt += mymp[presum];
            }
            if(mymp.find(presum - 1) != mymp.end()) {
                cnt += mymp[presum - 1];
            }      
        }
        return cnt;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值