• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C++实现LeetCode(164.求最大间距)

c++ 搞代码 4年前 (2022-01-06) 71次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了C++实现LeetCode(164.求最大间距),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

[LeetCode] 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 eleme来源gaodai#ma#com搞@代~码网nts, 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.

遇到这类问题肯定先想到的是要给数组排序,但是题目要求是要线性的时间和空间,那么只能用桶排序或者基排序。这里用桶排序 Bucket Sort 来做,首先找出数组的最大值和最小值,然后要确定每个桶的容量,即为 (最大值 – 最小值) / 个数 + 1,在确定桶的个数,即为 (最大值 – 最小值) / 桶的容量 + 1,然后需要在每个桶中找出局部最大值和最小值,而最大间距的两个数不会在同一个桶中,而是一个桶的最小值和另一个桶的最大值之间的间距,这是因为所有的数字要尽量平均分配到每个桶中,而不是都拥挤在一个桶中,这样保证了最大值和最小值一定不会在同一个桶中,具体的证明博主也不会,只是觉得这样想挺有道理的,各位看官大神们若知道如何证明请务必留言告诉博主啊,参见代码如下:

 class Solution { public: int maximumGap(vector& nums) { if (nums.size() <= 1) return 0; int mx = INT_MIN, mn = INT_MAX, n = nums.size(), pre = 0, res = 0; for (int num : nums) { mx = max(mx, num); mn = min(mn, num); } int size = (mx - mn) / n + 1, cnt = (mx - mn) / size + 1; vector bucket_min(cnt, INT_MAX), bucket_max(cnt, INT_MIN); for (int num : nums) { int idx = (num - mn) / size; bucket_min[idx] = min(bucket_min[idx], num); bucket_max[idx] = max(bucket_max[idx], num); } for (int i = 1; i <cnt; ++i) { if (bucket_min[i] == INT_MAX || bucket_max[i] == INT_MIN) continue; res = max(res, bucket_min[i] - bucket_max[pre]); pre = i; } return res; } };

Github 同步地址:

https://github.com/grandyang/leetcode/issues/164 

参考资料:

https://leetcode.com/problems/maximum-gap

http://blog.gaodaimna/u011345136/article/details/41963051

https://leetcode.com/problems/maximum-gap/discuss/50642/radix-sort-solution-in-java-with-explanation

https://leetcode.com/problems/maximum-gap/discuss/50643/bucket-sort-java-solution-with-explanation-on-time-and-space

以上就是C++实现LeetCode(164.求最大间距)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++实现LeetCode(164.求最大间距)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址