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.
class Solution { public: int maximumGap(vector<int>& nums) { int n = nums.size(), mini, maxi, i, j, k, prev = -1, ans = 0; if(n < 2) return 0; mini = maxi = nums[0]; for(i = 1; i < n; i++) { if(nums[i] < mini) mini = nums[i]; if(nums[i] > maxi) maxi = nums[i]; } k = (maxi - mini) / n + 1; vector<vector<int>> v(n); for(i = 0; i < n; i++) { j = (nums[i] - mini) / k; if(0 == v[j].size()) { v[j].push_back(nums[i]); v[j].push_back(nums[i]); } else { v[j][0] = max(nums[i], v[j][0]); v[j][1] = min(nums[i], v[j][1]); } } for(i = 0; i < n; i++) { if(0 == v[i].size()) continue; if(prev != -1) { j = v[i][1] - v[prev][0]; ans = max(ans, j); } prev = i; } return ans; } };
将nums分为n组,每组k = (maxi - mini) / n + 1个数,分别求出每组的最大值和最小值。