码迷,mamicode.com
首页 > 其他好文 > 详细

[leedcode] Maximum Gap

时间:2014-12-30 01:45:54      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

题目:(Sort)

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.

 

题解:

桶排序!!

public class Solution {
    public int maximumGap(int[] num) {
        if(num==null||num.length<2)
           return 0;
           
        int min=num[0];
        int max=num[0];
        
        for(int i:num)
        {
           min= Math.min(min,i);
           max= Math.max(max,i);
        }
        
        int gap = (int)Math.ceil((double)(max-min)/(num.length-1));
        int [] bucketMin = new int [num.length-1];
        int [] bucketMax = new int [num.length-1];
        
        Arrays.fill(bucketMin, Integer.MAX_VALUE);
        Arrays.fill(bucketMax, Integer.MIN_VALUE);
        
        for(int i:num)
        {
            if(i==min||i==max)
              continue;
              
            int index = (i-min)/gap ;
            bucketMin[index] = Math.min(i,bucketMin[index]);
            bucketMax[index] = Math.max(i,bucketMax[index]);
        }
        
        int prev =min;
        int maxGap = Integer.MIN_VALUE;
        for(int i=0 ; i<num.length-1; i++)
        {
            if(bucketMin[i]==Integer.MAX_VALUE||bucketMax[i]==Integer.MIN_VALUE)
               continue ;
            
            maxGap=Math.max(bucketMin[i]-prev,maxGap);
            prev=bucketMax[i];
        }
        
        maxGap = Math.max(max-prev,maxGap);
        return maxGap;
    }
}

 

[leedcode] Maximum Gap

标签:

原文地址:http://www.cnblogs.com/fengmangZoo/p/4192746.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!