在 C++ 中計算差別為 k 的所有不同對


在本教程中,我們將討論一個程式,以找到差值為 k 的不同對。

為此,我們將獲得一個整數陣列和值 k。我們的任務是計算所有差值為 k 的不同對。

例項

 即時演示

#include<iostream>
using namespace std;
int count_diffK(int arr[], int n, int k) {
   int count = 0;
   //picking elements one by one
   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

更新於:2020-02-05

167 次瀏覽

開啟您的 職業生涯

完成課程認證

開始學習
廣告
© . All rights reserved.