標籤:
Maximum Gap
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Return 0 if the array contains less than 2 elements.
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.
如果不考慮題目中要求的Linear time/space,實際上只需要先sort,然後找到最大的就可以了。
1 class Solution { 2 public: 3 int maximumGap(vector<int> &num) { 4 5 if(num.size()<2) 6 return 0; 7 8 sort(num.begin(),num.end()); 9 int max=0;10 11 for(int i=0;i<num.size()-1;i++)12 {13 if(num[i+1]-num[i]>max) 14 max=num[i+1]-num[i]; 15 }16 return max;17 }18 };
符合題意的方法: 由於num中的數字肯定在[min,max]區間內,所以根據抽屜原理,假設num中有n個數字,則最大的gap必然要大於dis=(max-min)/(n-1),所以我們可以把num所在的範圍分成等間隔的區間,相鄰區間內的元素之間的最大差值,即為要尋找的gap
1 class Solution { 2 public: 3 int maximumGap(vector<int> &num) { 4 5 if(num.size()<2) return 0; 6 if(num.size()==2) return abs(num[0]-num[1]); 7 8 int n=num.size(); 9 int min,max,i;10 11 min=max=num[0];12 13 for(i=0;i<num.size();i++)14 {15 if(min>num[i]) min=num[i];16 if(max<num[i]) max=num[i];17 }18 19 // 找到區間間隔20 //注意此處,也可以寫成(max-min)/n+1,此時就不需要num.size()==2的邊界條件了 21 int dis=(max-min)/(n-1)+1;22 23 vector<vector<int> > bucket((max-min)/dis+1);24 25 for(i=0;i<n;i++)26 {27 int x=num[i];28 int index=(x-min)/dis;29 //把元素放入不同的區間中30 if(bucket[index].empty())31 {32 bucket[index].reserve(2);33 bucket[index].push_back(x);34 bucket[index].push_back(x);35 }36 else37 {38 if(bucket[index][0]>x) bucket[index][0]=x;39 if(bucket[index][1]<x) bucket[index][1]=x;40 }41 }42 43 int pre=0;44 int gap=0;45 46 //在相鄰的區間中(區間內有元素的相鄰區間)尋找最大的gap47 for(i=1;i<bucket.size();i++)48 {49 if(bucket[i].empty()) continue;50 51 int tmp=bucket[i][0]-bucket[pre][1];52 if(gap<tmp) gap=tmp;53 pre=i;54 }55 return gap;56 }57 };
【leetcode】Maximum Gap