ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 找出任何两个元素之间的最小差异 > 原文: [https://www.geeksforgeeks.org/find-minimum-difference-pair/](https://www.geeksforgeeks.org/find-minimum-difference-pair/) 给定一个未排序的数组,找到给定数组中任何一对之间的最小差。 **示例**: ``` Input : {1, 5, 3, 19, 18, 25}; Output : 1 Minimum difference is between 18 and 19 Input : {30, 5, 20, 9}; Output : 4 Minimum difference is between 5 and 9 Input : {1, 19, -4, 31, 38, 25, 100}; Output : 5 Minimum difference is between 1 and -4 ``` **方法 1(简单:`O(n^2)`** 一个简单的解决方案是使用两个循环。 ## C/C++ ``` // C++ implementation of simple method to find // minimum difference between any pair #include <bits/stdc++.h> using namespace std; // Returns minimum difference between any pair int findMinDiff(int arr[], int n) {    // Initialize difference as infinite    int diff = INT_MAX;    // Find the min diff by comparing difference    // of all possible pairs in given array    for (int i=0; i<n-1; i++)       for (int j=i+1; j<n; j++)           if (abs(arr[i] - arr[j]) < diff)                 diff = abs(arr[i] - arr[j]);    // Return min diff    return diff; } // Driver code int main() {    int arr[] = {1, 5, 3, 19, 18, 25};    int n = sizeof(arr)/sizeof(arr[0]);    cout << "Minimum difference is " << findMinDiff(arr, n);    return 0; } ```