maximum gap java_LeetCode 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.

题解:

桶排序(bucket sort)

假设有N个元素A到B.

bucket(桶)的大小bucketLen = max(1,(B - A) / (N - 1)), 注意bucketLen为0的情况,则最多会有(B - A) / bucketLen + 1个桶

对于数组中的任意整数K, 很容易通过算式loc = (K - A) / bucketLen找出其桶的位置,然后维护每一个桶的最大值和最小值

由于同一个桶内的元素之间的差值至多为bucketLen - 1,因此最终答案不会从同一个桶中选择,否则整体的range达不到B-A.

对于每一个非空的桶p,找出下一个非空的桶q,则q.min - p.max可能就是备选答案。返回所有这些可能值中的最大值。

Note: corner case [1,1,1,1]若元素都相同,range就是0,16行算bucket时需要保持bucket的长度大于等于1.否则17行就有除以0的error.

同时此情况maxGap = 0. 所以maxGap的初始化是0而不是Integer.MIN_VALUE.

Time Complexity: O(n).

Space O(n).

AC Java:

1 public classSolution {2 public int maximumGap(int[] nums) {3 if(nums == null || nums.length < 2){4 return 0;5 }6 //Calculate the range

7 int max =Integer.MIN_VALUE;8 int min =Integer.MAX_VALUE;9 int len =nums.length;10 for(int i = 0; i

15 //bucket length and number

16 int bucketLen = Math.max(1,(max-min)/(len-1)); //error

17 int buckNum = (max-min)/bucketLen + 1;18

19 //calculate nums[i] position in buckets and maintain the maximun and minmum of each bucket

20 int [] maxArr = new int[buckNum];21 int [] minArr = new int[buckNum];22 Arrays.fill(maxArr, Integer.MIN_VALUE);23 Arrays.fill(minArr, Integer.MAX_VALUE);24 for(int i = 0; i

30 int maxGap = 0;31 int preMax = maxArr[0];32 for(int i = 1; i

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值