Wednesday, January 21, 2015

Maximum Gap (LeetCode Sort)

Question: 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.

Idea: Bucket sort. Assume there are n elements, we construct n-1 buckets and put the n-2 elements (without the max and the min) into the bucket. For each bucket, we only keep the bucketMax and the bucketMin value. Due to pigeon hole theory, there must be at least one empty buckets. The potential max gap is on the two sides of the empty buckets.

Time: O(n) Space: O(n)

Code:
 public class Solution {  
   public int maximumGap(int[] num) {  
     if(num.length<2)  
       return 0;  
     int maxValue=num[0];  
     int minValue=num[0];  
     for(int i=0;i<num.length;i++)  
     {  
       maxValue=Math.max(maxValue,num[i]);  
       minValue=Math.min(minValue,num[i]);  
     }  
     if(maxValue==minValue)  
       return 0;  
     int numBucket=num.length-1;  
     int bucketSize=(int)Math.ceil(((double)(maxValue-minValue))/numBucket);  
     int[] bucketMax=new int[numBucket];  
     int[] bucketMin=new int[numBucket];  
     Arrays.fill(bucketMax,Integer.MIN_VALUE);  
     Arrays.fill(bucketMin,Integer.MAX_VALUE);  
     for(int i=0;i<num.length;i++)  
     {  
       if(num[i]==maxValue||num[i]==minValue)  
         continue;  
       int whichBucket=(num[i]-minValue)/bucketSize;  
       bucketMax[whichBucket]=Math.max(bucketMax[whichBucket],num[i]);  
       bucketMin[whichBucket]=Math.min(bucketMin[whichBucket],num[i]);  
     }  
     int maxGap=Integer.MIN_VALUE;  
     int pre=minValue;  
     for(int i=0;i<numBucket;i++)  
     {  
       if(bucketMax[i]==Integer.MIN_VALUE&&bucketMin[i]==Integer.MAX_VALUE)  
         continue;  
       maxGap=Math.max(maxGap,bucketMin[i]-pre);  
       pre=bucketMax[i];  
     }  
     maxGap=Math.max(maxGap,maxValue-pre);  
     return maxGap;  
   }  
 }  

No comments:

Post a Comment