当A是正在发现时,从两个数组中找到对,并且B是随机的,其总和等于给定值k

时间:2018-02-05 13:24:53

标签: c++ algorithm binary-search

我正在尝试计算两个数组中的对,A是递增排序的,B是随机排序的。而且我也在寻找一个K值,使得A [] + B [] = K,但是使用下面的代码,我得到的0应该给出真实的3,那么我的错误在哪里?

#include <iostream>

int countPairs(int A[], int B[], int m, int n, int K) {
    bool ispre = false;
    int count = 0;
    int left = 0;
    int right = n - 1;

    for (int i = 0; i < m; i++) {
        int value = K - A[i];
        while (left <= right) {
            int mid = (left + right) / 2;
            if (B[mid] == value) {
                ispre = true;
            } else if (B[mid] > value)
                right = mid - 1;
            else
                left = mid + 1;
        }
        if (ispre)
            count++;
        else {
            // value not found
            return false;
        }
    }

    return count;
}

int main() {
    int A[] = { 1, 2, 3, 4, 5, 6, 7 };
    int B[] = { 4, 1, 3, 5, 8 };

    int m = sizeof(A) / sizeof(A[0]);
    int n = sizeof(B) / sizeof(B[0]);
    int K = 10;
    cout << "Count = " << countPairs(A, B, m, n, K);
    return 0;
}

1 个答案:

答案 0 :(得分:-1)

#include <iostream>
using namespace std;
int countPairs(int A[], int B[], int m, int n, int K) {
    bool ispre = false;
    int count = 0;

    for (int i = 0; i < m; i++) {
        int left = 0;
        int right = m - 1;
        int value = K - B[i];
        while (left <= right) {
            int mid = (left + right) / 2;
            if (A[mid] == value) {
                ispre = true;
                count++;
                break;
            } else if (A[mid] > value)
                right = mid - 1;
            else
                left = mid + 1;
        }
    }
    return count;
}

int main() {
    int A[] = { 1, 2, 3, 4, 5, 6, 7 };
    int B[] = { 4, 1, 3, 5, 8 };

    int m = sizeof(A) / sizeof(A[0]);
    int n = sizeof(B) / sizeof(B[0]);
    int K = 10;
    cout << "Count = " << countPairs(A, B, m, n, K) << endl;
    return 0;
}