zoukankan      html  css  js  c++  java
  • 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了,画画就明白了
  • 相关阅读:
    LeetCode 130. 被围绕的区域 (DFS)
    LeetCode 200. 岛屿数量 (BFS)
    LeetCode 200. 岛屿数量 (DFS)
    Win10下Anaconda命令行相关操作
    LeetCode 53. 最大子序和
    从尾到头打印链表
    字符串逆序
    交换俩字符串
    LeetCode 147. 对链表进行插入排序
    LeetCode 面试题 02.08. 环路检测
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4483606.html
Copyright © 2011-2022 走看看