9 and a half for the given number of exercises solution to a problem

Title Description

It gives the number of integers, asking whether there is a pair of numbers and equal to a given number.

Input Format

Total three lines:
a first line is the integer \ (n-(0 \ n-lt \ 100000 Le) \) , expressed \ (n-\) integers.
The second line is the n integers. Is an integer in the range of \ (0 \) to \ (10 ^ 8 \) between.
The third line is an integer \ (m (0 \ Le m \ Le 2 ^ {30}) \) , and expressed the need.

Output Format

If present and m is a number of output two integers, small front, after a large, separated by a single space. If the number of the plurality of conditions are satisfied, the number of the smaller number of selected smaller. If the number can not be found to meet the requirements of the output line "NO".

Sample input

4
2 5 1 4
6

Sample Output

1 5

Topic analysis

This question can use the time complexity \ (O (n) \) of the double pointer method. (Interested students can find out)
but we come here to explain \ (O (nlogn) \) two decomposition.
For array \ (a_1, a_2, ..., a_n \) , the first thing we need to use the sortfunction to give them in ascending order.
Then we can from \ (1 \) to the \ (n-\) traverse coordinates \ (I \) , for \ (a [i] \) , we can \ ([i + 1, n ] \) This use interval range to find whether there is a binary element is equal to a \ (mA [I] \) .
Of course slightly, we go through when we must ensure \ (a [i] \ le m / 2 \) on it, because I am another element binary search is certainly \ (\ Le A [i] \) .
Codes are as follows:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n, m, a[maxn];
// check函数用于二分查找数组a[L,R]中是否存在值为num的元素
bool check(int num, int L, int R) {
    while (L <= R) {
        int mid = (L + R) / 2;
        if (a[mid] == num) return true;
        else if (a[mid] > num) R = mid - 1;
        else L = mid + 1;
    }
    return false;
}
int main() {
    cin >> n;
    for (int i = 1; i <= n; i ++) cin >> a[i];
    cin >> m;
    sort(a+1, a+1+n);   // 给数组a[1]到a[n]范围内的数从小到大排序
    for (int i = 1; i <= n && a[i] <= m/2; i ++) { // 开始遍历a[i]
        if (check(m - a[i], i+1, n)) {  // 对[i+1,n]区间范围内二分查找m-a[i]
            cout << a[i] << " " << m-a[i] << endl;
            return 0;
        }
    }
    puts("NO");
    return 0;
}

Guess you like

Origin www.cnblogs.com/zifeiynoip/p/11450637.html