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

164. Maximum Gap

时间:2017-05-20 10:10:56      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:tween   ted   linear   average   run   new   contain   math   res   

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)

 

164. Maximum Gap

标签:tween   ted   linear   average   run   new   contain   math   res   

原文地址:http://www.cnblogs.com/codeskiller/p/6880901.html

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