LeetCode 164. Maximum Gap

来源:互联网 发布:微信群淘宝客话术 编辑:程序博客网 时间:2024/05/29 09:27

LeetCode 164. Maximum Gap

问题来源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.

问题分析

给定一个未排序的数组,返回数组中两个数之间最大的间隔。
比如[1,4,6,7,10,2,3] 这里的最大间隔就是[7,10] 也就是3。这道题还要求了线性的时间复杂度和空间复杂度。所以就不能对数组先排序然后计算最大的间隔了。
这里就要引入新的排序算法。桶排序。

桶排序网上的教程已经很多了,我就不多介绍了,基本思路就是准备若干个桶,将在一定范围内的数放进去。对于这道题目来说,如果设置合适的桶范围,最后就不用考虑桶内部的结构,只需要考虑桶与桶之间的关系就可以了。
首先得到数组的最大值和最小值,获得总范围[min,max]

然后设定桶的宽度和桶的个数

  1. 桶的宽度(max-min)/nums.length+1

  2. 桶的个数(max-min)/len+1

将数字按照条件放到桶里。

然后遍历桶与桶之间元素的顺序得到最大的间隔。

代码如下

public int maximumGap(int[] nums) {    if(nums==null||nums.length<2) return 0;    int max = 0,min = Integer.MAX_VALUE;    for (int num: nums         ) {        max=Math.max(max,num);        min=Math.min(min,num);    }    int len = (max-min)/nums.length+1;    int[][] buckets = new int[2][(max-min)/len+1];    for (int num: nums         ) {        int index = (num-min)/len;        buckets[0][index] = buckets[0][index]==0?num:Math.min(num,buckets[0][index]);        buckets[1][index]=Math.max(num,buckets[1][index]);    }    int res = 0;    int pre =min;    for (int i = 0; i < buckets[0].length; i++) {        if(buckets[0][i]==0&&buckets[1][i]==0){            continue;        }else {            res = Math.max(res,buckets[0][i]==0?buckets[1][i]-pre:buckets[0][i]-pre);            pre = Math.max(buckets[0][i],buckets[1][i]);        }    }    return res;}

LeetCode学习笔记持续更新

GitHub地址 https://github.com/yanqinghe/leetcode

CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678