Maximum Gap

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.

思路:

  基数排序的应用

我的代码:

public class Solution {
    public int maximumGap(int[] nums) {
        if(nums==null || nums.length<2) return 0;
        radixSort(nums, 2, 32);
        int diff = Integer.MIN_VALUE;
        
        for(int i=1; i<nums.length; i++)
        {
            diff = Math.max(diff, nums[i]-nums[i-1]);
        }
        return diff;
    }
    private void radixSort(int[] nums,int radix, int distance) {  
        int length = nums.length;  
        int[] temp = new int[length];//用于暂存元素  
        int[] count = new int[radix];//用于计数排序  
        int divide = 1;  
        for (int i = 0; i < distance; i++) {  
            System.arraycopy(nums, 0,temp, 0, length);  
            Arrays.fill(count, 0);  
              
            for(int j=0; j<length; j++)
            {
                int tmpKey = (temp[j]/divide%radix);
                count[tmpKey]++;
            }
            for(int j=1; j<radix; j++)
            {
                count[j] = count[j]+count[j-1];
            }
            
            for(int j=length-1; j>=0; j--)
            {
                int tmpKey = (temp[j]/divide%radix);
                count[tmpKey]--;
                nums[count[tmpKey]] = temp[j];
            }
              
            divide = divide * radix;                  
        }  
                  
    }  
}
View Code

学习之处:

  • 基数排序最后一步要从后往前来,因为后面的比前面的大,最佳反例 2,33比较到第二位还是2,33 但是当比较到第三位就是 33,2了,画画就明白了

posted on 2015-05-06 23:33  zhouzhou0615  阅读(114)  评论(0编辑  收藏  举报

导航