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

Maximum Gap

时间:2015-05-07 00:49:56      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

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了,画画就明白了

Maximum Gap

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4483606.html

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