164. Maximum Gap

来源:互联网 发布:html5 大数据动态展示 编辑:程序博客网 时间:2024/04/29 07:51

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.


public class Solution {   public int maximumGap(int[] nums){int len=nums.length;if(len<2)return 0;BinarySearchTree1 bst=new BinarySearchTree1();for(int num :nums )bst.insert(num);return bst.maxgap();}}class BinarySearchTree1 {private static class BinaryNode{int element;BinaryNode left;BinaryNode right;BinaryNode(int theElement,BinaryNode lt,BinaryNode rt){element=theElement;left=lt;right=rt;}}private BinaryNode root;private BinaryNode pre=null;private int max;public BinarySearchTree1(){root=null;}public int maxgap(){inorder(root);return max;}public void insert(int x){root=insert(x, root);}private BinaryNode insert (int x,BinaryNode t){if(t==null)return new BinaryNode (x,null,null);int compareResult=x-t.element;if(compareResult<0)t.left=insert(x, t.left);else if (compareResult>0)t.right=insert(x, t.right);else {}return t;}public void  inorder(BinaryNode  node){if(node.left!=null)inorder(node.left);if(pre!=null){int dis=node.element-pre.element;if(dis>max)max=dis;}pre=node;if(node.right!=null)inorder(node.right);}}



以下摘自

https://segmentfault.com/a/1190000002732382

要求连续元素的最大差值,那必然要排序,但是又要求在O(n)的复杂度内完成,自然就想到了桶排序。维护leftright两个数组,left[i]表示第i个桶的最左端元素,right[i]表示第i个桶的最右端点元素。除最后一个桶之外,每个桶都是前闭后开,最后一个桶是前闭后闭。当元素落到相应的桶内就更新相应桶的最左最右元素值,当所有元素都放入桶中之后,对桶区间进行遍历,计算相邻桶的前桶最大元素和后桶最小元素的差值,最大差值即是题目所求。

这里需要注意的是,对于最小值为min,最大值为max,个数为n的数组,相邻元素的最大差值必然大于等于(max - min) / (n - 1),所以用这个值作为桶区间的长度,这样可以保证最大差值必然出现在桶和桶之间。特别考虑最大差值等于(max - min) / (n - 1)的情况,此时数组中每个相邻元素的差值都是(max - min) / (n - 1),那么每个桶内只要一个元素,同样最大差值出现在桶和桶之间,之前的计算方法依然适用。


public int maximumGap(int[] num){if (num.length < 2)return 0;int min = num[0], max = num[0], len = num.length;for (int i = 1; i < len; i++){min = Math.min(min, num[i]);max = Math.max(max, num[i]);}int step = (max - min) / (len - 1);step = step == 0 ? 1 : step;int[] left = new int[(max - min) / step + 1];int[] right = new int[(max - min) / step + 1];for (int i = 0; i < len; i++){int range = (num[i] - min) / step;left[range] = left[range] == 0 ? num[i] : Math.min(left[range],num[i]);right[range] = right[range] == 0 ? num[i] : Math.max(right[range],num[i]);}int maxGap = 0, preMax = 0, curMin = 0;for (int i = 0; i < left.length; i++){if (left[i] == 0 && right[i] == 0)continue;if (preMax == 0){preMax = right[i];continue;}curMin = left[i];maxGap = Math.max(maxGap, curMin - preMax);preMax = right[i];}return maxGap;}


0 0
原创粉丝点击