桶排序
桶排序定义
桶排序是一种基于分治思想、效率很高的排序算法,理想情况下对应的时间复杂度为
O
(
n
)
O(n)
O(n)。桶排序算法的实现思路是:将待排序序列中的元素根据规则分组,每一组采用快排、插入排序等算法进行排序,然后再按照次序将所有元素合并,就可以得到一个有序序列。
为了使桶排序更加高效,我们需要做到这两点:
- 在额外空间充足的情况下,尽量增大桶的数量
- 使用的映射函数能够将输入的 N N N个数据均匀的分配到 K K K个桶中
桶排序时间复杂度分析
1. 什么时候最快:当输入的数据可以均匀的分配到每一个桶中。
2. 什么时候最慢:当输入的数据被分配到了同一个桶中。
桶排序例题
LeetCode164. 最大间距
给定一个无序的数组
n
u
m
s
nums
nums,返回 数组在排序之后,相邻元素之间最大的差值。如果数组元素个数小于
2
2
2,则返回
0
0
0。
您必须编写一个在「线性时间」内运行并使用「线性额外空间」的算法。
提示:
1
<
=
n
u
m
s
.
l
e
n
g
t
h
<
=
1
0
5
1<=nums.length<= 10^5
1<=nums.length<=105
0
<
=
n
u
m
s
[
i
]
<
=
1
0
9
0<=nums[i]<=10^9
0<=nums[i]<=109
思路
使用桶排序:记录数组最大值 M a x Max Max,最小值 M i n Min Min。共有 n n n个数,那么这 n n n个数间共有 n − 1 n-1 n−1个间隔,这些数之间的间隔的最大值 ≥ ( M a x − M i n ) / ( n − 1 ) \ge(Max-Min)/(n-1) ≥(Max−Min)/(n−1)(由抽屉原理可以得知)。设置每个桶大小 x x x(左开右闭),那么每个桶的数的间隔最大为 x − 1 x-1 x−1,为使得最大间隔在桶之间,而不在桶内,需要满足 x − 1 < ( M a x − M i n ) / n − 1 x-1<(Max-Min)/n-1 x−1<(Max−Min)/n−1,设当缩小,即 ( n − 1 ) ( x − 1 ) ≤ ( M a x − M i n − 1 ) (n-1)(x-1)\le(Max-Min-1) (n−1)(x−1)≤(Max−Min−1),所以 x ≤ M a x − M i n − 1 + n − 1 n − 1 = M a x − M i n + n − 2 n − 1 x\le\frac{Max-Min-1+n-1}{n-1}=\frac{Max-Min+n-2}{n-1} x≤n−1Max−Min−1+n−1=n−1Max−Min+n−2。此时间隔最大值必然在桶之间。
代码
class Solution {
class Node {
int min, max;
boolean used;
public Node() {
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
used = false;
}
}
public int maximumGap(int[] nums) {
int n = nums.length;
int Min = Integer.MAX_VALUE, Max = Integer.MIN_VALUE;
for(int x : nums) {
Min = Math.min(Min, x);
Max = Math.max(Max, x);
}
if(n < 2 || Min == Max) {
return 0;
}
int x = (Max - Min - 1 + n - 1) / (n - 1);
Node[] nodes = new Node[n-1];
for(int i = 0; i < n - 1; i++) {
nodes[i] = new Node();
}
int res = 0;
for(int y : nums) {
if(y == Min) {
continue;
}
int idx = (y - Min - 1) / x;
if(!nodes[idx].used) {
nodes[idx].used = true;
}
nodes[idx].min = Math.min(nodes[idx].min, y);
nodes[idx].max = Math.max(nodes[idx].max, y);
}
for(int last = Min, i = 0; i < n - 1; i++) {
if(nodes[i].used) {
res = Math.max(res,nodes[i].min - last);
last = nodes[i].max;
}
}
return res;
}
}