zoukankan      html  css  js  c++  java
  • 164. 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.

     1 public class Solution {
     2     public int maximumGap(int[] nums) {
     3         // corner case:if the input is null or the length of the input array is zero or one
     4         if(nums==null||nums.length<2) return 0;
     5         int min = Integer.MAX_VALUE;
     6         int max = Integer.MIN_VALUE;
     7         //find the min and max of the array
     8         for(int i=0;i<nums.length;i++){
     9             min = Math.min(min,nums[i]);
    10             max = Math.max(max,nums[i]);
    11         }
    12         // Math.ceil is the min Integer that >= i;Math.floor is the max integer that <=i;
    13         // the gap represents the average gap value between two numbers
    14         int gap = (int)Math.ceil((double)(max-min)/(nums.length-1));
    15         int[] bucketsMax = new int[nums.length-1];
    16         int[] bucketsMin = new int[nums.length-1];
    17         Arrays.fill(bucketsMax,Integer.MIN_VALUE);
    18         Arrays.fill(bucketsMin,Integer.MAX_VALUE);
    19         // put numbers into buckets
    20         for(int i:nums){
    21             if(i==min||i==max) continue;
    22             int idx = (i-min)/gap;
    23             bucketsMax[idx] = Math.max(i,bucketsMax[idx]);
    24             bucketsMin[idx] = Math.min(i,bucketsMin[idx]);
    25         }
    26         int maxGap = Integer.MIN_VALUE;
    27         int previous = min;
    28         // find the max neighboring buckets
    29         for(int i=0;i<nums.length-1;i++){
    30             if(bucketsMin[i]==Integer.MAX_VALUE||bucketsMax[i] ==Integer.MIN_VALUE){
    31                 continue;
    32             }
    33             maxGap = Math.max(maxGap,bucketsMin[i]-previous);
    34             previous = bucketsMax[i];
    35         }
    36         maxGap = Math.max(maxGap,max - previous);
    37         return maxGap;
    38     }
    39 }
    40 // the total run time could be O(n) time,and the space complexity could be O(n)
  • 相关阅读:
    struts2重点——ValueStack和OGNL
    struts2基础——请求与响应、获取web资源
    struts2基础——最简单的一个例子
    servlet、filter、listener、interceptor之间的区别和联系
    服务器端组件
    自定义JSTL标签和函数库
    常见前端效果实现
    HTTP Cookie/Session
    获取动态SQL查询语句返回值(sp_executesql)
    WPF数据绑定
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6880901.html
Copyright © 2011-2022 走看看