• [leedcode] Maximum Gap


    题目:(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;
        }
    }
  • 相关阅读:
    jquey插件开发
    平常问题传送门
    Angular1实战总结01:了不起的$cacheFactory
    node基础15:events模块
    node基础14:连接数据库
    node基础13:异步流程控制
    node基础12:动态网页
    node基础11:接受参数
    node基础10:处理异常
    IOS子视图超过父视图frame后,无法交互响应
  • 原文地址:https://www.cnblogs.com/fengmangZoo/p/4192746.html
Copyright © 2020-2023  润新知