[LeetCode] Maximum Gap

This problem has a naive solution using sort and linear scan. The suggested solution uses the idea of bucket sort. The following is a C++ implementation of the suggested solution.

Suppose all the n elements in nums fall within [l, u], the maximum gap will not be smaller than gap = (u - l) / (n - 1). However, this gap may become 0 and so we take the maximum of it with 1 to guarantee that the gap used to create the buckets is meaningful.

Then there will be at most m = (u - l) / gap + 1 buckets. For each number num, it will fall in the k = (num - u) / gap bucket. After putting all elements of nums in the corresponding buckets, we can just scan the buckets to compute the maximum gap.

The maximum gap is only dependent on the maximum number of the current bucket and the minimum number of the next neighboring bucket (the bucket should not be empty). So we only store the minimum and the maximum of each bucket. Each bucket is initialized as {minimum = INT_MAX, maximum = INT_MIN} and then updated while updating the buckets.

Putting these together, we can have the following solution, barely a straight-forward implementation of the suggested solution.

复制代码
 1 class Solution {
 2 public:
 3     int maximumGap(vector<int>& nums) {
 4         int n = nums.size();
 5         if (n < 2) return 0;
 6         auto lu = minmax_element(nums.begin(), nums.end());
 7         int l = *lu.first, u = *lu.second;
 8         int gap = max((u - l) / (n - 1), 1);
 9         int m = (u - l) / gap + 1;
10         vector<vector<int>> buckets(m, {INT_MAX, INT_MIN});
11         for (int num : nums) {
12             int k = (num - l) / gap;
13             if (num < buckets[k][0]) buckets[k][0] = num;
14             if (num > buckets[k][1]) buckets[k][1] = num;
15         }
16         int i = 0, j;
17         gap = buckets[0][1] - buckets[0][0];
18         while (i < m) {
19             j = i + 1;
20             while (j < m && buckets[j][0] == INT_MAX && buckets[j][1] == INT_MIN)
21                 j++;
22             if (j == m) break;
23             gap = max(gap, buckets[j][0] - buckets[i][1]);
24             i = j;
25         }
26         return gap; 
27     }
28 };
复制代码

 

posted @   jianchao-li  阅读(283)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
阅读排行:
· 开发的设计和重构,为开发效率服务
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 从零开始开发一个 MCP Server!
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
点击右上角即可分享
微信分享提示