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

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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44189622/article/details/129591341
今日推荐