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.
Assume all elements in the array is 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.
If you do not consider the linear time/space required in the topic, you actually need to sort first and then find the largest one.
1 classSolution {2 Public:3 intMaximumgap (vector<int> &num) {4 5 if(Num.size () <2) 6 return 0; 7 8 sort (Num.begin (), Num.end ()); 9 intmax=0;Ten One for(intI=0; I<num.size ()-1; i++) A { - if(num[i+1]-num[i]>max) -max=num[i+1]-Num[i]; the } - returnMax; - } -};
Conform to test instructions method: Because NUM number in the [Min,max] range, so according to the drawer principle, assuming that NUM has n numbers, then the largest gap must be greater than dis= (max-min)/(n-1), so we can divide Num's range into equal intervals, The maximum difference between elements in the adjacent interval, which is the gap to be searched for
1 classSolution {2 Public:3 intMaximumgap (vector<int> &num) {4 5 if(Num.size () <2)return 0;6 if(num.size () = =2)returnABS (num[0]-num[1]);7 8 intn=num.size ();9 intmin,max,i;Ten Onemin=max=num[0]; A - for(i=0; I<num.size (); i++) - { the if(Min>num[i]) min=Num[i]; - if(Max<num[i]) max=Num[i]; - } - + //Find interval interval - //Note that this can also be written as a (max-min)/n+1, where the boundary condition of the num.size () ==2 is not required. + intdis= (max-min)/(n1)+1; A atvector<vector<int> > Buckets ((max-min)/dis+1); - - for(i=0; i<n;i++) - { - intx=Num[i]; - intindex= (x-min)/dis; in //put the elements into different intervals - if(Bucket[index].empty ()) to { +Bucket[index].reserve (2); - bucket[index].push_back (x); the bucket[index].push_back (x); * } $ ElsePanax Notoginseng { - if(bucket[index][0]>X) bucket[index][0]=x; the if(bucket[index][1]<X) bucket[index][1]=x; + } A } the + intPre=0; - intgap=0; $ $ //find the largest gap in an adjacent interval (an adjacent interval with elements within the interval) - for(i=1; I<bucket.size (); i++) - { the if(Bucket[i].empty ())Continue; - Wuyi inttmp=bucket[i][0]-bucket[pre][1]; the if(gap<tmp) gap=tmp; -Pre=i; Wu } - returnGap; About } $};
"Leetcode" Maximum Gap