标签:
题目:(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; } }
标签:
原文地址:http://www.cnblogs.com/fengmangZoo/p/4192746.html