1048 Find Coins (25分)——two pointers

sort排序

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    ios::sync_with_stdio(false);
    int N, M;
    cin >> N >> M;
    int* s = new int[N];
    for (int i = 0; i < N; ++i)
    {
        cin >> s[i];
    }
    sort(s,s+N);
    int V1, V2;
    int i = 0, j = N - 1;
    int found = 0;
    while (i < j)
    {
        if (s[i] + s[j] == M)
        {
            V1 = s[i];
            V2 = s[j];
            found = 1;
            break;
        }
        else if (s[i] + s[j] > M)
        {
            --j;
        }
        else
        {
            ++i;
        }
    }
    if (found)
        cout << V1 << " " << V2;
    else
        cout << "No Solution";
    return 0;
}

 

posted @ 2020-09-28 23:04  幻想Elapse  阅读(69)  评论(0编辑  收藏  举报