【LeetCode】164. Maximum Gap 最大间距(Hard)(JAVA)
题目地址: https://leetcode.com/problems/maximum-gap/
题目描述:
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Note:
- You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
- Try to solve it in linear time/space.
题目大意
给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。
如果数组元素个数小于 2,则返回 0。
说明:
- 你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。
- 请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。
解题方法
- 先排序,然后计算最大差值,用的时间复杂度 O(nlogn),没有满足题目 O(n) 的要求
- note: 测试用例编的不够用心,竟然没有看出和 O(n) 算法的差距
class Solution {
public int maximumGap(int[] nums) {
Arrays.sort(nums);
int res = 0;
for (int i = 1; i < nums.length; i++) {
res = Math.max(res, nums[i] - nums[i - 1]);
}
return res;
}
}
执行耗时:2 ms,击败了99.81% 的Java用户
内存消耗:38.9 MB,击败了65.53% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg)