【无标题】

Ashish有一个集合A,里面有n个正整数,配对规则如下:对于 | a[i] - a[j] | >= z,则 i 和 j 配对,每个数只能配对一次。求最大配对数。
Input
第一行输入两个正整数n和z。2<=n<2e5,1<=z<=1e9
第二行输入n个正整数 1<=ai<=1e9
Output
输出一个正整数,最多有多少对数字能够匹配
Examples
Input
4 2
1 3 3 7
Output
2
Input
5 5
10 9 5 8 7
Output
1

error1:lower_bound()
error exp: 4 2 1 3 4 5 answer: 2 Myoutput: 1
最后看题解:发现这个情况不够准确,同时答案最大是n/2个,用整数二分(双指针)可以做对。

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 200021;
long long a[N];
bool st[N];
int main()
{
    int n,z; cin>>n>>z; int ans = 0;
    for(int i = 0; i < n; ++i) cin>>a[i];
    sort(a, a+ n); 
    // 对 1 2 45 46 这类数组来说,也是可以的;
    int le = 0, ri = (n+1)/2; 
    while(le <= n && ri <= n) {
        if(a[ri] - a[le] >= z) ans++, le++;
        ri++;
    }
    cout<<ans;
}```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

golemon.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值