LeetCode 164. Maximum Gap

本文提供了一种使用桶排序解决LeetCode上“最大间隔”问题的方法,详细介绍了如何通过计算桶的大小和数量来找到数组中最大间隔,并附上了Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.com/problems/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 class Solution {
 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<len; i++){
11             max = Math.max(max,nums[i]);
12             min = Math.min(min,nums[i]);
13         }
14         
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<len; i++){
25             int loc = (nums[i]-min)/bucketLen;
26             maxArr[loc] = Math.max(maxArr[loc],nums[i]);
27             minArr[loc] = Math.min(minArr[loc],nums[i]);
28         }
29         //Calculate maximum gap
30         int maxGap = 0;
31         int preMax = maxArr[0];
32         for(int i = 1; i<buckNum; i++){
33             if(maxArr[i] == Integer.MIN_VALUE || minArr[i] == Integer.MAX_VALUE){
34                 continue;
35             }
36             maxGap = Math.max(maxGap, minArr[i]-preMax);
37             preMax = maxArr[i];
38         }
39         return maxGap;
40     }
41 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4938081.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值