PAT甲级 1048 Find Coins(25) (双指针)

题目

Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she could only use exactly two coins to pay the exact amount. Since she has as many as 10^{5} coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find two coins to pay for it.

输入

Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (≤10^{5}, the total number of coins) and M (≤10^{3}, the amount of money Eva has to pay). The second line contains N face values of the coins, which are all positive numbers no more than 500. All the numbers in a line are separated by a space.

输出

For each test case, print in one line the two face values V1​ and V2​ (separated by a space) such that V1​+V2​=M and V1​≤V2​. If such a solution is not unique, output the one with the smallest V1​. If there is no solution, output No Solution instead.

样例输入 

8 15
1 2 8 7 2 4 11 15

7 14
1 8 7 2 4 11 15

样例输出 

4 11

No Solution

题意理解

题意很好理解就是给你n个数,然后给你一个数x问你能否在这n个数中找到两个数加起来是x,但是要注意的是不能同一个数的两倍变成我们想要找到的目标数。那么我们采用双指针算法。先对数组进行一个升序的排序,左指针 i 右指针 j 如果a[i]+a[j]>x,那么我们要找的那个目标只可能在右指针左边,那么我们移动右指针,如果小于或者等于那么左指针自动移动,一旦等于的话说明我们找到了那个目标,那么输出并且break掉即可,标记一下找到了。最后如果没找到的话那就输出No Solution

代码 

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int a[N];
int n,x;
int main(){
    cin>>n>>x;
    for(int i=1;i<=n;i++)cin>>a[i];
    sort(a+1,a+1+n);
    int fl=0;
    for(int i=1,j=n;i<=n;i++){
        while(j&&j!=i&&a[i]+a[j]>x)j--;
        if(a[i]+a[j]==x&&i!=j){
            cout<<a[i]<<" "<<a[j]<<endl;
            fl=1;
            break;
        }
    }
    if(!fl)puts("No Solution");
    return 0;
}


版权声明:本文为NHS6671原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。