LeetCode---(164)Maximum Gap
来源:互联网 发布:哈工大数据集 编辑:程序博客网 时间:2024/05/17 01:33
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) { if(nums.size()<2) return 0; sort(nums.begin(),nums.end()); int max=0; for(int i=1;i<nums.size();i++) { if(nums[i]-nums[i-1]>max) max=nums[i]-nums[i-1]; } return max; }};
虽然我们可以通过以上的代码,但是仔细看题目我们发现,我们并没有满足题目中所要求的时间复杂度(STL函数sort()的复杂度是O(nlogn)),然后我们考虑,可以借鉴桶排序的做法
思路是这样的:数组中有N个元素,最小的元素为min,最大的元素为max,那么最大的间距将不小于ceil((max-min)/(N-1))。(其中,ceil(x)指的是不小于x的最小整数)。假设平均间距为gap=ceil((max-min)/(N-1)),把所有的元素放进N-1个桶里,第k(0<=k<=N-2)个桶里放所有位于区间[min+k*gap, min+(k+1)*gap)内的元素。因此除了最大的元素max和最小的元素min,其余的N-2个元素都被放进这N-1个桶里,因此至少有一个桶是空的,我们只需要存储每个桶里最大的元素和最小的元素就可以算出最大的间距是多少。
具体代码如下
class Solution {public: int maximumGap(vector<int>& nums) { if(nums.size()<2) return 0; int min=nums[0],max=nums[0]; int nSize=nums.size(); for(int i=0;i<nSize;i++) { if(nums[i]<min) min=nums[i]; else if(nums[i]>max) max=nums[i]; } if(nSize==2) return max-min; //每个桶的大小,向上取整。 int bucket_length=(max-min)/(nSize-1)+1; //桶的个数:(max - min) / bucket_length + 1,每个桶里面存储属于该桶的最大值和最小值即可,注意这里的最大最小值是局部的 int bucket_num=(max - min) / bucket_length + 1; vector<vector<int>> bucket(bucket_num); for(int i=0;i<nSize;i++) { int index=(nums[i]-min)/bucket_length; if(bucket[index].empty()){ bucket[index].reserve(2); bucket[index].push_back(nums[i]); bucket[index].push_back(nums[i]); }else{ if(bucket[index][0]>nums[i]) bucket[index][0]=nums[i]; if(bucket[index][1]<nums[i]) bucket[index][1]=nums[i]; } } int res=0; int pre=0; for(int i=1;i<bucket.size();i++) { if(bucket[i].empty()) continue; if(bucket[i][0]-bucket[pre][1]>res) res=bucket[i][0]-bucket[pre][1]; pre=i; } return res; }};
0 0
- LeetCode(164) Maximum Gap
- [leetcode 164] Maximum Gap
- LeetCode---(164)Maximum Gap
- LeetCode #164 Maximum Gap
- leetcode 164: Maximum Gap
- LeetCode 164 Maximum Gap
- Leetcode 164 Maximum Gap
- [Leetcode] #164 Maximum Gap
- [leetcode-164]Maximum Gap(c)
- LeetCode(164)Maximum Gap
- leetcode:sort:Maximum Gap(164)
- leetcode:sort:Maximum Gap(164)
- Leetcode 164 Maximum Gap (最大差距)
- leetcode-Maximum Gap
- [LeetCode] Maximum Gap
- LeetCode Maximum Gap
- [leetCode] Maximum Gap
- leetcode 155: Maximum Gap
- 正则表达式
- 学习笔记(一)初始化与清理
- c++动态绑定、静态绑定与java中动态绑定与静态绑定的比较
- 黑马day05 URL重写
- float数据在计算机内存中的存储方法
- LeetCode---(164)Maximum Gap
- JavaDB数据库操作练习
- java 任意两个时间差,天数,小时数,分钟数,秒数
- 黑马程序员--java学习笔记第五天
- ScrollView中嵌套ListView,TextView只显示一行的高度解决方案
- 拉格朗日对偶性的一些总结
- 解决 debian8 中 /etc/default/docker 无效问题
- 黑马程序员--静态代理和动态代理
- Virtual, Linear, and Physical Addresses