#include //************************************************ // HackerRank Prepare > Algorithms > Search: Pairs //************************************************ // Given an array of integers and a target value, determine the number // of pairs of array elements that have a difference equal to the // target value. using namespace std; int pairs(int k, vector arr) { sort(arr.begin(), arr.end()); int count = 0; size_t i = 0, j = 1; while (j < arr.size()) { if (arr[j] - arr[i] == k) { count++; j++; } else if (arr[j] - arr[i] < k) { j++; } else if (arr[j] - arr[i] > k) { i++; } } return count; } int main() { vector,int>> v = { // k arr expected { 2, {1,5,3,4,2}, 3 }, { 1, {363374326,364147530,61825163,1073065718,1281246024,1399469912,428047635,491595254,879792181,1069262793}, 0 }, { 2, {1,3,5,8,6,4,2},5 }, }; for (auto i: v) { int k = get<0>(i); vector& arr = get<1>(i); int expected = get<2>(i); int result = pairs(k, arr); cout << result << endl; cout << expected << endl; cout << "--------------\n"; } return 0; }