GH1995 / leetcode-test-and-run

方便 leetcode 刷题的小工具
GNU General Public License v2.0
0 stars 0 forks source link

164. Maximum Gap 求最大间距 #39

Open GH1995 opened 5 years ago

GH1995 commented 5 years ago

164. Maximum Gap

Difficulty: Hard

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:

Solution

Language: C++

class Solution {
public:
    int maximumGap(vector<int> &nums) {
      if (nums.empty()) return 0;
​
      int minVal = *min_element(nums.begin(), nums.end());
      int maxVal = *max_element(nums.begin(), nums.end());
​
      int bucket_size = (maxVal - minVal) / nums.size() + 1; // 桶的容量
      int bucket_nums = (maxVal - minVal) / bucket_size + 1; // 桶的数目
​
      vector<int> bucket_min(bucket_nums, INT_MAX);
      vector<int> bucket_max(bucket_nums, INT_MIN);
​
      set<int> s;
      for (int d: nums) {
        int idx = (d - minVal) / bucket_size;
​
        bucket_min[idx] = min(bucket_min[idx], d);
        bucket_max[idx] = max(bucket_max[idx], d);
​
        s.insert(idx);
      }
​
      // 计算gap
      int pre = 0, res = 0;
      for (int i = 1; i < nums.size(); ++i) {
        if (!s.count(i))
          continue;
​
        res = max(res, bucket_min[i] - bucket_max[pre]);
        pre = i;
      }
​
      return res;
    }
};