C ++:在整数数组中查找对,其线性时间总和等于10

时间:2017-03-02 22:21:59

标签: c++ algorithm

我正在练习C++并且在线性时间内无法做到这一点:

// Find pairs in an integer array whose sum is equal to 10 (bonus: do it in linear time)
#include <vector>
#include <iostream>

int main(int argc, char const *argv[]) {
    using std::vector;

    std::vector<int> foo = {1,2,4,3,1,3,1,4,5,15,5,2,3,5,4};

    int i = 0;

    int j = foo.size() - 1;

    int a = 0, b = 0;

    while (i < j) {
        a = foo[i], b = foo[j];
        std::cout << a << " " << b << "\n";
        if ( a + b == 10) {break;}
        else if (a + b < 10) { i++;}
        else if (a + b > 10) { j--;}
    }

    std::cout << "a = " << a << " and b = " << b << "\n";
    return 0;
}

这会错误地打印a = 15 and b = 5

0 个答案:

没有答案