LeetCode-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.

Solution:

 1 public class Solution {
 2     public int maximumGap(int[] num) {
 3         int len = num.length;
 4         if (len<2) return 0;
 5         if (len==2) return num[1]-num[0];
 6 
 7         int numMax = num[0], numMin = num[0];
 8         for (int i:num){
 9             numMax = Math.max(numMax,i);
10             numMin = Math.min(numMin,i);
11         }
12         double temp = (double) numMax - numMin;
13             int gap = (int) Math.ceil(temp/(len-1));
14 
15         int[] bucketMin = new int[len-1];
16         int[] bucketMax = new int[len-1];
17         Arrays.fill(bucketMin, Integer.MAX_VALUE);
18         Arrays.fill(bucketMax, Integer.MIN_VALUE);
19         for (int i:num){
20             int index = (i-numMin)/gap;
21             if (i==numMax) index = len-2;
22             if (i>bucketMax[index]) bucketMax[index] = i;
23             if (i<bucketMin[index]) bucketMin[index] = i;
24         }
25 
26         int res = Integer.MIN_VALUE;
27         int pre = bucketMax[0];
28         for (int i=1;i<len-1;i++)
29             if (bucketMin[i] == Integer.MAX_VALUE) continue;
30             else {
31                 if (res<(bucketMin[i]-pre))
32                     res = bucketMin[i]-pre;
33                 pre = bucketMax[i];
34             }
35         
36         return res;
37     }
38 }

 

转载于:https://www.cnblogs.com/lishiblog/p/4200261.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值