LeetCode -- 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.
You can directly use the sorting algorithm built in. net (or other programming languages), and then find the maximum value by calculating the interval.
The following is the simplest implementation method. Call the sort (the internal implementation is the fast sorting of stable) of LINQ and then calculate the interval.
public class Solution { public int MaximumGap(int[] nums) { if(nums == null || nums.Length < 2){ return 0; } var lst = nums.OrderBy(n=>n).ToList(); var max = 0; for(var i = 0;i < lst.Count - 1; i++){ max = Math.Max(max, lst[i+1] - lst[i]); } return max; }}
The official answer is to use bucket sorting:
1. obtain the maximum and minimum values. A total of nums. Length/(max-min) buckets are required.
2. Determine which bucket nums [I] belongs in the Process of traversing nums, and then put the elements in the specified bucket.
3. Maintain the maximum and minimum values of each bucket
4. traverse the maximum values of the bucket, the interval between them (the minimum value of the bucket [I-1] and the maximum value of the bucket [I)
public class Solution { public int MaximumGap(int[] nums) { if(nums == null || nums.Length < 2){ return 0; } // find the max and min int max = nums[0]; int min = nums[0]; for(int i = 1; i < nums.Length; i++){ max = Math.Max(max, nums[i]); min = Math.Min(min, nums[i]); } // init bucket var buckets = new Bucket[nums.Length + 1]; for(int i=0; i < buckets.Length; i++){ buckets[i] = new Bucket(); } double height = (double) nums.Length / (max - min);// bucket height // loop each element in nums, find the bucket for it. for(int i=0; i