Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2488. Count Subarrays With Median K

Rain Hu

2488. Count Subarrays With Median 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:

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. Hash Map

int countSubarrays(vector<int>& nums, int k) {
    vector<int> presum = {0};
    int pivot;
    for (int i = 0; i < nums.size(); i++) {
        int back = presum.back();
        if (nums[i] > k) {
            back += 1;
        } else if (nums[i] < k){
            back -= 1;
        } else {
            pivot = i+1;
        }
        presum.push_back(back);
    }
    int res = 0;
    
    unordered_map<int,int> map;
    for (int i = 0; i < pivot; i++) map[presum[i]]++;
    
    for (int i = pivot; i < presum.size(); i++) {
        res += (map[presum[i]] + map[presum[i]-1]);
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 446. Arithmetic Slices II - Subsequence
Next
[LeetCode] 2487. Remove Nodes From Linked List