164. Maximum Gap
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1] Output: 3 Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10] Output: 0 Explanation: The array contains less than 2 elements, therefore return 0.
Note:
- You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
- Try to solve it in linear time/space.
AC code:
class Solution { public: int maximumGap(vector<int>& nums) { int len = nums.size(); if (len < 2) return 0; int minn = nums[0]; int maxx = nums[0]; for (int i = 1; i < len; ++i) { minn = min(minn, nums[i]); maxx = max(maxx, nums[i]); } int gaps = (int)ceil((double)(maxx - minn) / (len-1)); // the numbers of burket vector<int> gap_min(len-1, INT_MAX); vector<int> gap_max(len-1, INT_MIN); for (int i = 0; i < len; ++i) { if (nums[i] == minn || nums[i] == maxx) continue; int idx = (nums[i] - minn) / gaps; gap_min[idx] = min(gap_min[idx], nums[i]); gap_max[idx] = max(gap_max[idx], nums[i]); } int maxdis = INT_MIN; int prev = minn; for (int i = 0; i < len-1; ++i) { if (gap_min[i] == INT_MAX && gap_max[i] == INT_MIN) continue; maxdis = max(maxdis, gap_min[i] - prev); prev = gap_max[i]; } maxdis = max(maxx-prev, maxdis); return maxdis; } };
Runtime: 8 ms, faster than 56.67% of C++ online submissions for Maximum Gap.
Analylis:
step1:
calculating numbers between the min number and the max number in the array.
step2:
using gaps buckets to equallt distributed the numbers.
step3:
find the max and min numbers in each buckets.
step4:
the maximum gap is max(gaps, buckets[i]'s min_number - buckets[i-1]'s max_number);
永远渴望,大智若愚(stay hungry, stay foolish)