請設計一個複雜度爲O(n)的算法,計算一個未排序數組中排序後相鄰元素的最大差值。算法
給定一個整數數組A和數組的大小n,請返回最大差值。保證數組元素個數大於等於2小於等於500。數組
[9,3,1,10],4
返回:6
class MaxDivision { public: int findMaxDivision(vector<int> A, int n) { make_heap(A.begin(),A.end()); sort_heap(A.begin(),A.end()); int max = 0,tmp; for(int i=1;i<n;i++) { tmp = A[i]-A[i-1]; max = tmp>max ? tmp:max; } return max; } };
不明白上述方法爲何能夠經過調試????測試
class MaxDivision { public: int findMaxDivision(vector<int> A, int n) { // write code here set<int> s; set<int>::iterator iter; set<int>::iterator iter2; for(int i=0;i<n;i++) s.insert(A[i]); iter=s.begin(); int max=0; int first=*iter; int second=*iter; for(iter=s.begin();iter!=s.end();++iter) { if(*iter>first) { second=*iter; if(second-first>max) { max=second-first; } first=second; } } return max; } };
public static int findMaxDivision(int[] A, int n) { int maxnum = A[0]; int minnum = A[0]; for (int i = 0; i < A.length; i++) { if (maxnum < A[i]) maxnum = A[i]; if (minnum > A[i]) minnum = A[i]; } int[] arr = new int[maxnum - minnum + 1]; // 生成桶 for (int i = 0; i < A.length; i++) { arr[A[i] - minnum]++; // 填桶 } int count = 0; int max = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] == 0) { // 桶爲空 count++; //記錄連續空桶數 } else { if (max < count) max = count; count = 0; } } return max+1; //如最大值爲9,最小值爲3,中間有5個空桶,但差值應爲6 }
https://www.nowcoder.com/questionTerminal/376ede61d9654bc09dd7d9fa9a4b0bcdspa