Sum of two numbers (dichotomy)

  • topic

   Given an array and a specific value m, find two numbers from the array and make their sum m.

 

  •  Algorithm idea

    The first solution is to use a double loop to enumerate all numbers, with a complexity of O (n ^ 2).

for (int i=0; i<n-1; i++)
   for (int j=i+1; j<n; j++)
        if (a[i]+a[j] == m)
            break;

    Solution two is to sort the array first, and then for each element a [i] of the array, the dichotomy finds whether the array is equal to ma [i], and the complexity is O (nlogn).

do {
    int mid = l + (r-l)/2;
    if (a[mid] == x) return mid;        // 遍历x为m-a[i]
    else if (a[mid] > x) return r = mid-1;
    else l = mid+1;
} while (l<=r);

 

  • answer     
#include <iostream>
using namespace std;
#define maxn 100010
int binarysearch(int a[], int size, int x) {
    int l=0, r=size-1;
    do {
        int mid = l + (r-l)/2;            // 防止溢出
        if (a[mid] == x) return mid;    
        else if (a[mid] > x) r = mid-1;
        else l = mid+1;
    } while (l<=r);

    return -1;
}


int main() {
    int a[maxn],n, m;
    cin >> n >> m;
    for (int i=0; i<n; i++)                // 输入数组
        cin >> a[i];
    
    for (int i=0; i<n; i++) {              // 遍历搜索m-a[i]
        int tmp = binarysearch(a,n,m-a[i]);
        if (a[tmp] + a[i] == m && tmp != i) {
            cout << i << "," << tmp << endl;
            break;
        }
    }
    

    return 0;
}

 

Published 21 original articles · praised 8 · visits 1495

Guess you like

Origin blog.csdn.net/K_Xin/article/details/87862077