<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # 計算所有等于 k 的不同對 > 原文: [https://www.geeksforgeeks.org/count-pairs-difference-equal-k/](https://www.geeksforgeeks.org/count-pairs-difference-equal-k/) 給定一個整數數組和一個正整數 k,對所有不同的對進行計數,其差等于 k。 **示例**: ``` Input: arr[] = {1, 5, 3, 4, 2}, k = 3 Output: 2 There are 2 pairs with difference 3, the pairs are {1, 4} and {5, 2} Input: arr[] = {8, 12, 16, 4, 0, 20}, k = 4 Output: 5 There are 5 pairs with difference 4, the pairs are {0, 4}, {4, 8}, {8, 12}, {12, 16} and {16, 20} ``` **方法 1(簡單)** 一個簡單的解決方案是逐一考慮所有對,并檢查每對之間的差異。 以下程序實現簡單的解決方案。 我們運行兩個循環:外部循環選擇對的第一個元素,內部循環尋找另一個元素。 如果數組中有重復項,則此解決方案將不起作用,因為要求僅計算不重復的對。 ## C++ ```cpp /* A simple program to count pairs with difference k*/ #include<iostream> using namespace std; int countPairsWithDiffK(int arr[], int n, int k) { ????int count = 0; ????// Pick all elements one by one ????for (int i = 0; i < n; i++) ????{??????? ????????// See if there is a pair of this picked element ????????for (int j = i+1; j < n; j++) ????????????if (arr[i] - arr[j] == k || arr[j] - arr[i] == k ) ??????????????????count++; ????} ????return count; } // Driver program to test above function 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 " ?????????<< countPairsWithDiffK(arr, n, k); ????return 0; } ``` ## Java ```java // A simple Java program to? //count pairs with difference k import java.util.*; import java.io.*; class GFG { ????static int countPairsWithDiffK(int arr[],? ????????????????????????????????????int n, int k) ????{ ????????int count = 0; ????????// Pick all elements one by one ????????for (int i = 0; i < n; i++)? ????????{ ????????????// See if there is a pair ????????????// of this picked element ????????????for (int j = i + 1; j < n; j++) ????????????????if (arr[i] - arr[j] == k || ????????????????????arr[j] - arr[i] == k) ????????????????????count++; ????????} ????????return count; ????} ????// Driver code ????public static void main(String args[]) ????{ ????????int arr[] = { 1, 5, 3, 4, 2 }; ????????int n = arr.length; ????????int k = 3; ????????System.out.println("Count of pairs with given diff is " ????????????????????????+ countPairsWithDiffK(arr, n, k)); ????} } // This code is contributed? // by Sahil_Bansall ``` ## Python3 ```py # A simple program to count pairs with difference k def countPairsWithDiffK(arr, n, k): ????count = 0 ????# Pick all elements one by one ????for i in range(0, n): ????????# See if there is a pair of this picked element ????????for j in range(i+1, n) : ????????????if arr[i] - arr[j] == k or arr[j] - arr[i] == k: ????????????????count += 1 ????return count # Driver program arr = [1, 5, 3, 4, 2] n = len(arr) k = 3 print ("Count of pairs with given diff is ", ????????????????countPairsWithDiffK(arr, n, k)) ``` ## C# ```cs // A simple C# program to count pairs with? // difference k using System; class GFG { ????static int countPairsWithDiffK(int []arr,? ????????????????????????????????int n, int k) ????{ ????????int count = 0; ????????// Pick all elements one by one ????????for (int i = 0; i < n; i++)? ????????{ ????????????// See if there is a pair ????????????// of this picked element ????????????for (int j = i + 1; j < n; j++) ????????????????if (arr[i] - arr[j] == k || ??????????????????????arr[j] - arr[i] == k) ????????????????????count++; ????????} ????????return count; ????} ????// Driver code ????public static void Main() ????{ ????????int []arr = { 1, 5, 3, 4, 2 }; ????????int n = arr.Length; ????????int k = 3; ????????Console.WriteLine("Count of pairs with " ?????????????????????????????+ " given diff is " ???????????????+ countPairsWithDiffK(arr, n, k)); ????} } // This code is contributed by Sam007\. ``` ## PHP ```php <?php // A simple PHP program to count? // pairs with difference k function countPairsWithDiffK($arr, $n, ???????????????????????????????????$k) { ????$count = 0; ????// Pick all elements one by one ????for($i = 0; $i < $n; $i++) ????{? ????????// See if there is a pair of ????????// this picked element ????????for($j = $i + 1; $j < $n; $j++) ????????????if ($arr[$i] - $arr[$j] == $k or ????????????????$arr[$j] - $arr[$i] == $k) ????????????????$count++; ????} ????return $count; } ????// Driver Code ????$arr = array(1, 5, 3, 4, 2); ????$n = count($arr); ????$k = 3; ????echo "Count of pairs with given diff is " ????????, countPairsWithDiffK($arr, $n, $k); // This code is contributed by anuj_67\. ?> ``` Output : ``` Count of pairs with given diff is 2 ``` `O(n^2)`的時間復雜度 **方法 2(使用排序)** 我們可以使用 O(nLogn)排序算法(例如[合并排序](http://geeksquiz.com/merge-sort/),[堆排序[](http://geeksquiz.com/heap-sort/) 等。以下是詳細步驟。 ``` 1) Initialize count as 0 2) Sort all numbers in increasing order. 3) Remove duplicates from array. 4) Do following for each element arr[i] a) Binary Search for arr[i] + k in subarray from i+1 to n-1. b) If arr[i] + k found, increment count. 5) Return count. ``` ## C++ ``` /* A sorting based program to count pairs with difference k*/ #include <iostream> #include <algorithm> using namespace std; /* Standard binary search function */ int binarySearch(int arr[], int low, int high, int x) { ????if (high >= low) ????{ ????????int mid = low + (high - low)/2; ????????if (x == arr[mid]) ????????????return mid; ????????if (x > arr[mid]) ????????????return binarySearch(arr, (mid + 1), high, x); ????????else ????????????return binarySearch(arr, low, (mid -1), x); ????} ????return -1; } /* Returns count of pairs with difference k in arr[] of size n. */ int countPairsWithDiffK(int arr[], int n, int k) { ????int count = 0, i; ????sort(arr, arr+n);? // Sort array elements ????/* code to remove duplicates from arr[] */ ????// Pick a first element point ????for (i = 0; i < n-1; i++) ????????if (binarySearch(arr, i+1, n-1, arr[i] + k) != -1) ????????????count++; ????return count; } // Driver program? 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 " ????????<< countPairsWithDiffK(arr, n, k); ????return 0; } ``` ## Java ```java // A sorting base java program to? // count pairs with difference k import java.util.*; import java.io.*; class GFG { ????// Standard binary search function // ????static int binarySearch(int arr[], int low,? ???????????????????????????????int high, int x) ????{ ????????if (high >= low)? ????????{ ????????????int mid = low + (high - low) / 2; ????????????if (x == arr[mid]) ????????????????return mid; ????????????if (x > arr[mid]) ????????????????return binarySearch(arr, (mid + 1), ??????????????????????????????????????????high, x); ????????????else ????????????????return binarySearch(arr, low,? ????????????????????????????????????(mid - 1), x); ????????} ????????return -1; ????} ????// Returns count of pairs with? ????// difference k in arr[] of size n.? ????static int countPairsWithDiffK(int arr[], int n, int k) ????{ ????????int count = 0, i; ????????// Sort array elements ????????Arrays.sort(arr); ????????// code to remove duplicates from arr[]? ????????// Pick a first element point ????????for (i = 0; i < n - 1; i++) ????????????if (binarySearch(arr, i + 1, n - 1, ?????????????????????????????arr[i] + k) != -1) ????????????????count++; ????????return count; ????} ????// Driver code ????public static void main(String args[]) ????{ ????????int arr[] = { 1, 5, 3, 4, 2 }; ????????int n = arr.length; ????????int k = 3; ????????System.out.println("Count of pairs with given diff is " ????????????????????????????+ countPairsWithDiffK(arr, n, k)); ????} } // This code is contributed by Sahil_Bansall ``` ## Python ``` # A sorting based program to? # count pairs with difference k # Standard binary search function? def binarySearch(arr, low, high, x): ????if (high >= low): ????????mid = low + (high - low)//2 ????????if x == arr[mid]: ????????????return (mid) ????????elif(x > arr[mid]): ????????????return binarySearch(arr, (mid + 1), high, x) ????????else: ????????????return binarySearch(arr, low, (mid -1), x) ????return -1 # Returns count of pairs with? # difference k in arr[] of size n.? def countPairsWithDiffK(arr, n, k): ????count = 0 ????arr.sort() # Sort array elements ????# code to remove? ????# duplicates from arr[]? ????# Pick a first element point ????for i in range (0, n - 2): ????????if (binarySearch(arr, i + 1, n - 1,? ?????????????????????????arr[i] + k) != -1): ????????????count += 1 ????return count # Driver Code? arr= [1, 5, 3, 4, 2] n = len(arr) k = 3 print ("Count of pairs with given diff is ", ?????????????countPairsWithDiffK(arr, n, k))? # This code is contributed # by Shivi_Aggarwal ``` ## C# ``` // A sorting base C# program to? // count pairs with difference k using System; class GFG { ????// Standard binary search function? ????static int binarySearch(int []arr, int low,? ????????????????????????????int high, int x) ????{ ????????if (high >= low)? ????????{ ????????????int mid = low + (high - low) / 2; ????????????if (x == arr[mid]) ????????????????return mid; ????????????if (x > arr[mid]) ????????????????return binarySearch(arr, (mid + 1), ??????????????????????????????????????????high, x); ????????????else ????????????????return binarySearch(arr, low,? ?????????????????????????????????????(mid - 1), x); ????????} ????????return -1; ????} ????// Returns count of pairs with? ????// difference k in arr[] of size n.? ????static int countPairsWithDiffK(int []arr,? ???????????????????????????????????int n, int k) ????{ ????????int count = 0, i; ????????// Sort array elements ????????Array.Sort(arr); ????????// code to remove duplicates from arr[]? ????????// Pick a first element point ????????for (i = 0; i < n - 1; i++) ????????????if (binarySearch(arr, i + 1, n - 1, ????????????????????????????arr[i] + k) != -1) ????????????????count++; ????????return count; ????} ????// Driver code ????public static void Main() ????{ ????????int []arr = { 1, 5, 3, 4, 2 }; ????????int n = arr.Length; ????????int k = 3; ????????Console.WriteLine("Count of pairs with" ????????????????????????????+ " given diff is " ??????????????+ countPairsWithDiffK(arr, n, k)); ????} } // This code is contributed by Sam007\. ``` ## PHP ```php <?php // A sorting based PHP program to // count pairs with difference k // Standard binary search function function binarySearch($arr, $low, ??????????????????????$high, $x) { ????if ($high >= $low) ????{ ????????$mid = $low + ($high - $low)/2; ????????if ($x == $arr[$mid]) ????????????return $mid; ????????if ($x > $arr[$mid]) ????????????return binarySearch($arr, ($mid + 1),? ??????????????????????????????????????$high, $x); ????????else ????????????return binarySearch($arr, $low, ???????????????????????????????($mid -1), $x); ????} ????return -1; } /* Returns count of pairs with ???difference k in arr[] of size n. */ function countPairsWithDiffK($arr, $n, $k) { ????$count = 0; ????$i; ????// Sort array elements ????sort($arr);? ????// Code to remove duplicates? ????// from arr[] ????// Pick a first element point ????for ($i = 0; $i < $n - 1; $i++) ????????if (binarySearch($arr, $i + 1, $n - 1,? ?????????????????????????$arr[$i] + $k) != -1) ????????????$count++; ????return $count; } ????// Driver Code ????$arr = array(1, 5, 3, 4, 2); ????$n = count($arr); ????$k = 3; ????echo "Count of pairs with given diff is " ?????????, countPairsWithDiffK($arr, $n, $k); // This code is contributed by anuj-67\. ?> ``` **輸出**: ``` Count of pairs with given diff is 2 ``` 時間復雜度:第一步(排序)需要 O(nLogn)時間。 第二步運行二分搜索 n 次,因此第二步的時間復雜度也是 O(nLogn)。 因此,總體時間復雜度為 O(nLogn)。 第二步可以優化為`O(n)`,請參見。 **方法 3(使用自平衡 BST)** 我們也可以使用自平衡 BST(例如 [AVL 樹](https://www.geeksforgeeks.org/avl-tree-set-1-insertion/)或紅黑樹)來解決此問題。 以下是詳細的算法。 ``` 1) Initialize count as 0. 2) Insert all elements of arr[] in an AVL tree. While inserting, ignore an element if already present in AVL tree. 3) Do following for each element arr[i]. a) Search for arr[i] + k in AVL tree, if found then increment count. b) Search for arr[i] - k in AVL tree, if found then increment count. c) Remove arr[i] from AVL tree. ``` 上述解決方案的時間復雜度也是 O(nLogn),因為自平衡二叉樹的搜索和刪除操作花費 O(Logn)時間。 **方法 4(使用散列)** 在許多情況下,我們也可以使用散列來實現平均時間復雜度為`O(n)`。 ``` 1) Initialize count as 0. 2) Insert all distinct elements of arr[] in a hash map. While inserting, ignore an element if already present in the hash map. 3) Do following for each element arr[i]. a) Look for arr[i] + k in the hash map, if found then increment count. b) Look for arr[i] - k in the hash map, if found then increment count. c) Remove arr[i] from hash table. ``` 哈希在`O(n)`時間內起作用的非常簡單的情況是值范圍很小的情況。 例如,在以下實現中,數字范圍假定為 0 到 99999。可以使用將值用作索引的簡單哈希技術。 ``` /* An efficient program to count pairs with difference k when the range ???numbers is small */ #define MAX 100000 int countPairsWithDiffK(int arr[], int n, int k) { ????int count = 0;? // Initialize count ????// Initialize empty hashmap. ????bool hashmap[MAX] = {false}; ????// Insert array elements to hashmap ????for (int i = 0; i < n; i++) ????????hashmap[arr[i]] = true; ????for (int i = 0; i < n; i++) ????{ ????????int x = arr[i]; ????????if (x - k >= 0 && hashmap[x - k]) ????????????count++; ????????if (x + k < MAX && hashmap[x + k]) ????????????count++; ????????hashmap[x] = false; ????} ????return count; } ``` **方法 5(使用排序)** * 排序數組 arr * 取兩個指針 l 和 r,都指向第一個元素 * 取差 arr [r] – arr [l] * 如果 diff 值為 K,則遞增計數并將兩個指針都移至下一個元素 * 如果值 diff > k,則將 l 移至下一個元素 * 如果值 diff < k,則將 r 移至下一個元素 * 退貨計數 ## C++ ``` /* A sorting based program to count pairs with difference k*/ #include <iostream> #include <algorithm> using namespace std; /* Returns count of pairs with difference k in arr[] of size n. */ int countPairsWithDiffK(int arr[], int n, int k) { ????int count = 0; ????sort(arr, arr+n);? // Sort array elements ????int l = 0; ????int r = 0; ????while(r < n) ????{ ?????????if(arr[r] - arr[l] == k) ????????{ ??????????????count++; ??????????????l++; ??????????????r++; ????????} ?????????else if(arr[r] - arr[l] > k) ??????????????l++; ?????????else // arr[r] - arr[l] < sum ??????????????r++; ????}??? ????return count; } // Driver program to test above function 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 " ?????????<< countPairsWithDiffK(arr, n, k); ????return 0; } ``` ## Java ```java // A sorting based Java program to? // count pairs with difference k import java.util.*; class GFG { /* Returns count of pairs with difference k in arr[] of size n. */ static int countPairsWithDiffK(int arr[], int n, ??????????????????????????????????????????int k) { ????int count = 0; ????Arrays.sort(arr); // Sort array elements ????int l = 0; ????int r = 0; ????while(r < n) ????{ ????????if(arr[r] - arr[l] == k) ????????{ ????????????count++; ????????????l++; ????????????r++; ????????} ????????else if(arr[r] - arr[l] > k) ????????????l++; ????????else // arr[r] - arr[l] < sum ????????????r++; ????}? ????return count; } // Driver program to test above function public static void main(String[] args) { ????int arr[] = {1, 5, 3, 4, 2}; ????int n = arr.length; ????int k = 3; ????System.out.println("Count of pairs with given diff is " + ????????????????????????countPairsWithDiffK(arr, n, k)); } } // This code is contributed by Prerna Saini ``` ## Python3 ```py # A sorting based program to? # count pairs with difference k def countPairsWithDiffK(arr,n,k): ????count =0 ????# Sort array elements ????arr.sort()? ????l =0 ????r=0 ????while r<n: ????????if arr[r]-arr[l]==k: ????????????count+=1 ????????????l+=1 ????????????r+=1 ????????# arr[r] - arr[l] < sum ????????elif arr[r]-arr[l]>k:? ????????????l+=1 ????????else: ????????????r+=1 ????return count # Driver code if __name__=='__main__': ????arr = [1, 5, 3, 4, 2] ????n = len(arr) ????k = 3 ????print("Count of pairs with given diff is ", ??????????countPairsWithDiffK(arr, n, k)) # This code is contributed by? # Shrikant13 ``` ## C# ``` // A sorting based C# program to count? // pairs with difference k using System; class GFG { ????/* Returns count of pairs with ????difference k in arr[] of size n. */ ????static int countPairsWithDiffK(int []arr,? ????????????????????????????????int n, int k) ????{ ????????int count = 0; ????????// Sort array elements ????????Array.Sort(arr); ????????int l = 0; ????????int r = 0; ????????while(r < n) ????????{ ????????????if(arr[r] - arr[l] == k) ????????????{ ????????????????count++; ????????????????l++; ????????????????r++; ????????????} ????????????else if(arr[r] - arr[l] > k) ????????????????l++; ????????????else // arr[r] - arr[l] < sum ????????????????r++; ????????}? ????????return count; ????} ????// Driver program to test above function ????public static void Main() ????{ ????????int []arr = {1, 5, 3, 4, 2}; ????????int n = arr.Length; ????????int k = 3; ????????Console.Write("Count of pairs with " ????????????????????????+ "given diff is " + ????????????countPairsWithDiffK(arr, n, k)); ????} } // This code is contributed by nitin mittal. ``` ## PHP ```php <?php // A sorting based program to count // pairs with difference k // Returns count of pairs with? // difference k in arr[] of size n. function countPairsWithDiffK( $arr, $n, $k) { ????$count = 0; ????// Sort array elements ????sort($arr);? ????$l = 0; ????$r = 0; ????while($r < $n) ????{ ????????if($arr[$r] - $arr[$l] == $k) ????????{ ????????????$count++; ????????????$l++; ????????????$r++; ????????} ????????else if($arr[$r] - $arr[$l] > $k) ????????????$l++; ????????// arr[r] - arr[l] < k ????????else? ????????????$r++; ????}? ????return $count; } ????// Driver Code ????$arr = array(1, 5, 3, 4, 2); ????$n =count($arr); ????$k = 3; ????echo "Count of pairs with given diff is " ????????, countPairsWithDiffK($arr, $n, $k); // This code is contributed by anuj_67, ?> ``` **輸出**: ``` Count of pairs with given diff is 2 ``` 時間復雜度:O(nlogn)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看