题目原文:
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.
题目大意:
给出一个无序的数组,求出排序后相邻两个元素差的最大值。如果数组长度小于2,则返回0.
题目分析:
懒得做了,直接按题面要求做。
源码:(language:java)
public class Solution {
public int maximumGap(int[] nums) {
if(nums.length<2)
return 0;
Arrays.sort(nums);
int maxgap = Integer.MIN_VALUE;
for(int i = 1;i<nums.length;i++) {
if(nums[i]-nums[i-1]>maxgap)
maxgap=nums[i]-nums[i-1];
}
return maxgap;
}
}
成绩:
4ms,beats 92.15%,众数6ms,27.29%
Cmershen的碎碎念:
不知道leetcode后台的test case怎么设计的,有很多题用朴素解法比绞尽脑汁想出的低复杂度算法还要快。
本文提供了一种解决方案,用于找出给定无序数组在排序后相邻元素间的最大差距。通过直接排序并遍历数组来计算最大差值,适用于非负整数且数量不超过32位整数范围的情况。
179

被折叠的 条评论
为什么被折叠?



