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.
Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.
1 class Solution { 2 public: 3 int maximumGap(vector<int>& nums) { 4 if(nums.size()<2) return 0; 5 sort(nums.begin(),nums.end()); 6 int max=0; 7 for(int i=1;i<nums.size();i++) 8 { 9 if(nums[i]-nums[i-1]>max) 10 max=nums[i]-nums[i-1]; 11 } 12 return max; 13 14 } 15 };
时间: 2024-10-09 22:14:49