题目
给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。
如果数组元素个数小于 2,则返回 0。
示例 1:
输入: [3,6,9,1]
输出: 3
解释: 排序后的数组是[1,3,6,9]
, 其中相邻元素 (3,6)
和 (6,9)
之间都存在最大差值 3
。
示例 2:
输入: [10]
输出: 0
解释: 数组元素个数小于 2
,因此返回0
。
说明:
- 你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。
- 请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。
解题思路
考虑用分桶法,一个数组最小值为low
,最大值为high
,如果数组在low
和high
之间均匀分布,得到的最大差值是最小的,比如数组[1,3,5,7,9]
,差值为2
,而数组[1,3,4,5,9]
,最大差值是4
,虽然两个数组最小值和最大值以及元素数目均相同。
所以考虑分桶,桶的容量为(high-low)/n
,其中n
为元素的数组,则 最大差值一定大于桶的容量 。而桶的个数为(high-low)/桶的容量+1
,然后找出每个桶的最大值和最小值,那么最大差值一定是桶之间的最大间隔。
代码
class Solution {
public:
int maximumGap(vector<int>& nums) {
int n=nums.size();
if(n<=1) return 0;
int low=nums[0],high=nums[0];
//low high表示数组中最小值和最大值
for(auto m:nums){
low=min(low,m);
high=max(high,m);
}
int count=(high-low)/n;
//两种case [2 2 2 2 2] 和[1 1 1 3 3 3 3 3 3]
if(high==low) return 0;
else if(count==0) count=1;
vector<vector<int>> res((high-low)/count+1,vector<int>(2,-1));
for(auto m:nums){
int t=(m-low)/count;
res[t][0]=res[t][0]==-1?m:min(res[t][0],m);
res[t][1]=res[t][1]==-1?m:max(res[t][1],m);
}
int gap=0,left=-1;
for(int i=0;i<res.size();i++){
if(res[i][0]==-1) continue;
else if(left!=-1)
gap=max(gap,res[i][0]-left);
left=res[i][1];
}
return gap;
}
};
方法二
代码:
class Solution {
public:
int maximumGap(vector<int>& nums) {
int n=nums.size(),res=0;
set<int> s;
for(auto &m:nums) s.insert(m);
for(auto &m:nums){
auto it=s.find(m);
if(it!=s.begin()){
it--;
res=max(res,m-(*it));
}
}
return res;
}
};