思路:排序+二分
代码:
#include <iostream> #include <vector> #include <algorithm> using namespace std; bool BinSerch(const vector<int>& arr, int start, int target) { int left = start; int right = arr.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return true; } else if (arr[mid] < target) { left = mid + 1; } else if (arr[mid] > target) { right = mid - 1; } } return false; } // 待实现函数,在此函数中填入答题代码 int Proc(const vector<int>& arr, int diff) { // 在此添加你的代码 size_t arrLen = arr.size(); vector<int> arrCur; arrCur.assign(arr.begin(), arr.end()); int cnt = 0; sort(arrCur.begin(), arrCur.end()); for (size_t i = 0; i < arrLen - 1; i++) { if ((diff > 0 && BinSerch(arrCur, i + 1, arrCur[i] + diff)) || (diff < 0 && BinSerch(arrCur, i + 1, arrCur[i] - diff))) { cnt++; } } return cnt; } // 以下为考题输入输出框架,此部分代码不建议改动 int main() { string line; getline(cin, line); int diff = stoi(line); getline(cin, line); int n = stoi(line); vector<int> arr(n); for (int i = 0; i < n; ++i) { cin >> arr[i]; } cout << Proc(arr, diff) << endl; return 0; }