原题
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.
分析
其实就是先排序,再找连续两个元素差的最大值,题目要求线性的时间和空间复杂度,常见的这种类型的算法有计数排序,基数排序,桶排序。。这里偷了个懒直接STL的sort了。
class Solution {
public:
int maximumGap(vector<int>& nums) {
if(nums.size()<2)
return 0;
sort(nums.begin(),nums.end());
int res=0;
for(int i=0;i<nums.size()-1;++i)
{
res=max(res,nums[i+1]-nums[i]);
}
return res;
}
};