有一个整形数组A,请设计一个复杂度为O(n)的算法,算出排序后相邻两数的最大差值。
给定一个int数组A和A的大小n,请返回最大的差值。保证数组元素多于1个。
#include <iostream> #include <vector> using namespace std; class Gap { public: int maxGap(vector<int> A, int n) { int var_max = A[0], var_min = A[0]; for(int i = 1; i < n; i++){ if(var_max < A[i]) var_max = A[i]; if(var_min > A[i]) var_min = A[i]; } if(var_max == var_min) return 0; double var_unit = (double)(var_max - var_min)/(double)n; // vector<int> bucket[n+1]; vector<vector<int> > bucket(n+1); for(int i = 0; i < n; i++){ bucket[getIndex(var_unit, A[i], var_min)].push_back(A[i]); } int res = -1, tmp; int index1 = 0, index2 = 1; while(index2 < n+1){ // cout<<"index1: "<<index1<<"|| index2: "<<index2<<endl; if(!bucket[index1].empty() && !bucket[index2].empty()){ tmp = getMin(bucket[index2]) - getMax(bucket[index1]); index1++, index2++; if(tmp > res) res = tmp; } if(bucket[index1].empty()) index1++; if(bucket[index2].empty()) index2++; } return res; } int getIndex(double var_unit, int var, int var_min){ return ((double)(var-var_min)/var_unit); } int getMax(vector<int> A){ int tmp = A[0]; for(int i = 1; i < A.size(); i++){ if(tmp < A[i]) tmp = A[i]; } return tmp; } int getMin(vector<int> A){ int tmp = A[0]; for(int i = 1; i < A.size(); i++){ if(tmp > A[i]) tmp = A[i]; } return tmp; } }; int main() { vector<int> A; //3429,6401,8559,1052,4775,6220,3593,2406,4995 A.push_back(3429), A.push_back(6401), A.push_back(8559), A.push_back(1052), A.push_back(4775); A.push_back(6220), A.push_back(3593), A.push_back(2406), A.push_back(4995); Gap sorter; int res = sorter.maxGap(A, 9); cout<<res<<endl; return 0; }