51nod 1001 数组中和等于K的数对(二分)

51nod 1001 数组中和等于K的数对(二分)

题解: 用sort排下序,然后每个用二分找到的符合的下标j,判断此下标对应的值是不是你要找的。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <queue>
#include <stack>
#include <vector>
using namespace std;
#define INF 0x3f3f3f
#define pi acos(-1.0)
#define MAX 1000010
#define N 50010

int a[N];
int bsearch_zou(int begin,int end, int e)
{
    int mid,left = begin, right = end;
    while(left <= right)
    {
        mid = (left + right) >> 1;
        if(a[mid] >= e)
            right = mid-1;
        else
            left = mid+1;
    }
    return left;
}
int main()
{
    int k,n;
    while(~scanf("%d%d",&k,&n))
    {
        for(int i = 0; i < n; i++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        int ans = 0;
        int flag = 0;
        for(int i = 0; i < n; i++)
        {
            int x = k - a[i];
            int l = bsearch_zou(i+1, n-1, x);
            if(a[l] == x)
            {
                flag = 1;
                printf("%d %d\n",a[i],x);
            }
        }
        if(flag == 0)
            printf("No Solution\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值