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.
[分析]
直接的思路是调用Arrays.sort排序数组,然后依次比较相邻元素,求出最大gap,但Arrays.sort使用快速排序,时间复杂度是O(nlogn),不满足题目要求。 那么线性排序算法有哪些呢?计数排序、基数排序、桶排序,此题可用桶排序解决。
Leetcode的参考解法思路如下:
Suppose there are N elements and they range from A to B.
Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]
Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket.
For any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.
Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.
For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.
style2是自己第二次写的实现,注意:
1)仅有两个数时直接返回差值的绝对值
2)min 和 max 相等时可直接返回
3)桶的长度不超过ceil((max - min) / (n - 1))时就无需比较桶内的gap.
桶的个数取 n 而不是 n - 1,考虑case [100, 1,2,3] 此时min + (n - 1) * minGap = max, 等号正好成立,若桶取 n - 1该case会在运行时数组越界。
[ref]
http://blog.csdn.net/u012162613/article/details/41936569
// style 2
public class Solution {
public int maximumGap(int[] nums) {
if (nums == null || nums.length < 2)
return 0;
if (nums.length == 2) // edge case 1
return Math.abs(nums[1] - nums[0]);
// find min and max in nums[]
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for (int a : nums) {
min = Math.min(min, a);
max = Math.max(max, a);
}
if (min == max) return 0; // edge case 2
// calculate bucket width
int n = nums.length;
// int bucketWidth = (int)Math.ceil((double)(max - min) / (n - 1)); // use n buckets,
int bucketWidth = (int)Math.ceil((double)(max - min) / (n - 1));
// init buckets
int[] minInBucket = new int[n];
int[] maxInBucket = new int[n];
Arrays.fill(minInBucket, Integer.MAX_VALUE);
Arrays.fill(maxInBucket, Integer.MIN_VALUE);
// populate nums into correct bucket
for (int a : nums) {
int idx = (a - min) / bucketWidth;
minInBucket[idx] = Math.min(minInBucket[idx], a);
maxInBucket[idx] = Math.max(maxInBucket[idx], a);
}
// search the max inter bucket gap
int maxGap = 0;
int prev = maxInBucket[0];
for (int i = 1; i < n; i++) {
if (minInBucket[i] == Integer.MAX_VALUE) continue;
maxGap = Math.max(maxGap, minInBucket[i] - prev);
prev = maxInBucket[i];
}
return maxGap;
}
}
// style 1
public class Solution {
// http://blog.csdn.net/u012162613/article/details/41936569
public int maximumGap(int[] nums) {
if (nums == null || nums.length < 2)
return 0;
// find the max & min of the nums
int max = nums[0], min = nums[0];
for (int num : nums) {
if (num > max) max = num;
if (num < min) min = num;
}
// calculate bucket info
int N = nums.length;
int bucketLen = (max - min) / (N - 1) + 1;
int bucketNum = (max - min) / bucketLen + 1;
int[][] buckets = new int[bucketNum][2];
boolean[] bucketNonEmpty = new boolean[bucketNum];
// update num in bucket, each bucket only contains max & min of number belong to this bucket
for (int num : nums) {
int bucketId = (num - min) / bucketLen;
if (bucketNonEmpty[bucketId]) {
if (num > buckets[bucketId][1]) buckets[bucketId][1] = num;
if (num < buckets[bucketId][0]) buckets[bucketId][0] = num;
} else {
bucketNonEmpty[bucketId] = true;
buckets[bucketId][0] = num;
buckets[bucketId][1] = num;
}
}
// calculate max gap
int maxGap = buckets[0][1] - buckets[0][0];
int prev = 0;
for (int i = 1; i < bucketNum; i++) {
if (bucketNonEmpty[i]) {
maxGap = Math.max(maxGap, buckets[i][0] - buckets[prev][1]);
prev = i;
}
}
return maxGap;
}
}
分享到:
相关推荐
java java_leetcode-maximum-depth-of-binary-tree
《在IDE中高效进行LeetCode练习:leetcode-editor的深度解析》 在编程学习与技能提升的过程中,LeetCode作为一款广受欢迎的在线编程挑战平台,帮助众多开发者锻炼算法思维,提高编程能力。而为了进一步提升练习体验...
在IDE中解决LeetCode问题,支持leetcode.com与leetcode-cn.com,满足基本的做题需求。 理论上支持: IntelliJ IDEA PhpStorm WebStorm PyCharm RubyMine AppCode CLion GoLand DataGrip Rider MPS Android Studio。
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
LeetCode Editor 7.4 版本的下载是一个名为 "leetcode-editor" 的压缩包文件。这个压缩包的导入过程非常简单,只需要将它直接拖入 IDEA 界面,IDEA 会自动识别并安装插件。这种方式使得安装过程无需额外的步骤,对于...
~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/vsc-leetcode-cli/bin/leetcode /usr/local/bin/leetcode 修改模板 open ~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/...
leetcode-习题集资源leetcode-习题集资源leetcode-习题集资源leetcode-习题集资源leetcode-习题集资源leetcode-习题集资源
解题思路思路和LeetCode-python 503.下一个更大元素 II一致,只是这里求的是下标的距离,而不是数值倒序搜索,用到栈,栈里存储索引情况1:若栈为
《PyPI官网下载 | leetcode-export-1.1.tar.gz》 在编程世界里,LeetCode是一个备受程序员喜爱的在线平台,它提供了大量的算法题目,帮助开发者提升编程技能和解决问题的能力。而Python作为一门广泛使用的高级编程...
javascript js_leetcode题解之164-maximum-gap.js
leetcode-习题集资源源代码leetcode-习题集资源源代码leetcode-习题集资源源代码leetcode-习题集资源源代码leetcode-习题集资源源代码
leetcode-cheat 的发布 它是什么 ? 这是一个chrome 扩展,可以帮助您更高效地使用 leetcode。您可以从 重要: leetcode-cheat 现在只支持中文版。 也就是说不完全支持leetcode.com,但是你可以用leetcode-cn.com代替...
`swift-Swif-LeetCode-Utils` 是一个实用工具库,它为Swift程序员提供了方便快捷的方法来处理这些问题。这个项目可以帮助你更高效地进行LeetCode上的编程练习,提升你的解决方案的可读性和简洁性。 首先,让我们...
java java_leetcode-115-distinct-subsquences
java java_leetcode-112-path-sum
java java_leetcode-101-symmetric-tree
java java_leetcode-100-same-tree
970. 强整数对数运算function powerfulIntegers(x: number, y: number, bound: number): numb
java java_leetcode-110-balanced-binary-tree