和为 40 的两个下标
在 13 15 17 23 24 里找和为 40 的两个数。运行下面这段程序:
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
using namespace std;
pair<int, int> two_sum(const vector<int>& a, int target) {
int lo = 0;
int hi = (int)a.size() - 1;
while (lo < hi) {
int s = a[lo] + a[hi];
if (s == target) return {lo, hi};
if (s < target) lo++;
else hi--;
}
return {-1, -1};
}
int main() {
auto p = two_sum({13, 15, 17, 23, 24}, 40);
cout << p.first << "/" << p.second << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)