• 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)
  • 相关阅读:
    SDN网络笔记【毕设-SDN网络】
    Latex笔记【Latex】
    小米路由器 3G 开启SSH 安装 MT 工具箱 【环境搭建,小米路由器】
    windows 下安装linux子系统及其可视化【Linux】
    11月1日数据结构讨论班 【杂】
    简单远程遥控程序【网络程序设计
    VPS使用小结【VPS】
    vim使用总结【Vim】
    域名解析【网络程序设计
    MySQL数据库修改字段名、字段类型、字段长度
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6880901.html
Copyright © 2020-2023  润新知