题解 | #中位数#

中位数

https://ac.nowcoder.com/acm/contest/11177/A

B

提供一个比较简单实现的思路

首先一个数在这个区间是第大,等价于有个数是小于等于这个数的

我们不妨将所有小于等于的数都变成1,将所有大于的数都变成0

这样通过查询区间的和,就能判断是否有个数小于等于

通过前缀和算法,可以加速查询,问题转化成了有多少个,满足

由于原数组是一个的排列,所以只会出现一次,设它的位置是

我们令开始遍历,对于每个,我们想知道有多少,这个查询可以用map预处理出来

时间复杂度

#include <iostream>
#include <cstring>
#include <algorithm>
#include <map>
#define int long long
using namespace std;
typedef long long ll;

const int N = 200005;
ll a[N], b[N];
ll n, x, k;
map<ll, ll> mp;
signed main()
{
    scanf("%lld%lld%lld", &n, &x, &k);
    int pos ;
    for(int i = 1; i <= n; i ++ )
    {
        scanf("%lld", &a[i]);
        if(a[i] == x) pos = i;
        if(a[i] <= x) b[i] = 1;
        else b[i] = 0;
    }
    mp[0] ++ ;
    for(int i = 1; i <= n; i ++ )
    {
        b[i] = b[i - 1] + b[i];
        if(i < pos) mp[b[i]] ++ ;
    }
    int cnt = 0;
    for(int i = pos; i <= n; i ++ )
    {
        cnt += mp[b[i] - k];
    }
    cout << cnt;
    return 0;
}
全部评论
大佬,mp[0] 为什么要++呀
点赞 回复 分享
发布于 2021-08-23 21:22
浇浇我d题,康师傅
点赞 回复 分享
发布于 2021-08-22 17:35
你这不是nlogn吗。。开个桶不就n了
点赞 回复 分享
发布于 2021-08-21 12:14

相关推荐

09-02 11:14
已编辑
四川大学 Java
吴offer选手:这种面试是最烦的,学不到东西,然后还被挂的莫名其妙。之前看到一种说法是面试官如果不想要你了,就会问一些很简单的问题,防止你举报他
点赞 评论 收藏
分享
评论
11
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务