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) { if (nums == null || nums.length < 2) { return 0; } int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { min = Math.min(min, nums[i]); max = Math.max(max, nums[i]); } if (min == max) { return 0; } boolean[] hasNum = new boolean[nums.length+1]; int[] maxs = new int[nums.length+1]; int[] mins = new int[nums.length+1]; int bid = 0; for (int i = 0; i < nums.length; i++) { bid = bucket(nums[i], nums.length, min, max); mins[bid] = hasNum[bid] ? Math.min(mins[bid], nums[i]) : nums[i]; maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], nums[i]) : nums[i]; hasNum[bid] = true; } int res = 0; int lastMax = 0; int i = 0; while (i <= nums.length) { if (hasNum[i++]) { lastMax = maxs[i-1]; break; } } for (; i <= nums.length; i++) { if (hasNum[i]) { res = Math.max(res, mins[i]-lastMax); lastMax = maxs[i]; } } return res; } private int bucket(long num, long length, long min, long max) { // TODO Auto-generated method stub return (int) ((num - min) * length / (max - min)); } }