在本教程中,我们将讨论一个程序来查找差异等于k的不同对。
为此,我们将提供一个整数数组和值k。我们的任务是将所有具有差异的不同对作为k进行计数。
#include<iostream> using namespace std; int count_diffK(int arr[], int n, int k) { int count = 0; //一一挑选元素 for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) if (arr[i] - arr[j] == k || arr[j] - arr[i] == k ) count++; } return count; } int main(){ int arr[] = {1, 5, 3, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout << "Count of pairs with given diff is" << count_diffK(arr, n, k); return 0; }
输出结果
Count of pairs with given diff is 2