您的位置:首页 > 其它

【LeetCode】164.Maximum Gap(Hard)解题报告

2018-03-02 15:12 375 查看
【LeetCode】164.Maximum Gap(Hard)解题报告

题目地址:https://leetcode.com/problems/maximum-gap/description/

题目描述:

  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:

/*
看到排序,还要求线性时间空间复杂度,就要想到桶排序,bucket sort。
挺难的一道题,目的是找到排序之后的最大间隔。
1  3  5  9
min = 1
max = 9
gap = 3
1  4  7  9

bucketsMin: 3 5 INF    区间中的最小值
bucketsMax: 3 5 -INF   区间中的最大值

time : O(n)
space : O(n)
*/
class Solution {
public int maximumGap(int[] nums) {
if(nums == null || nums.length < 2) return 0;

int len = nums.length;
int min = nums[0];
int max = nums[0];
for(int i=0 ; i<nums.length ; i++){
min = Math.min(min , nums[i]);
max = Math.max(max , nums[i]);
}

int gap = (int)Math.ceil((double)(max - min)/(len - 1));
int[] bucketsMin = new int[len - 1];
int[] bucketsMax = new int[len - 1];
Arrays.fill(bucketsMin , Integer.MAX_VALUE);
Arrays.fill(bucketsMax , Integer.MIN_VALUE);
for(int num : nums){
if(num == min || num == max) continue;
int bucket = (num -min)/gap; //看在哪个区间里
bucketsMin[bucket] = Math.min(num , bucketsMin[bucket]);
bucketsMax[bucket] = Math.max(num , bucketsMax[bucket]);
}

int res = 0;
int pre = min;
for(int i=0 ; i<len-1 ; i++){
//区间里数没有
if(bucketsMin[i] == Integer.MAX_VALUE && bucketsMax[i] == Integer.MIN_VALUE){
continue;
}
res = Math.max(res , bucketsMin[i] - pre);
pre = bucketsMax[i];
}
//下面这句别忘了,最大值还没算
res = Math.max(res , max-pre);
return res;
}
}


Date:2018年3月2日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode array