Description
牛客网 2018校招真题 最大差值
Solving Ideas
如果数组长度为n,则使用n+1个桶,每个桶能放入数的范围固定,将数组中的数依次放入桶中,最终最大差值出现在相邻两个不为空的桶之间。
因为第一个桶会被放入所有元素中的最小值,最后一个桶会被放入所有元素中的最大值,也即第一个桶和最后一个桶必定不为空,那么空桶一定不会出现在首尾。例如:
有数组10,25,34,43,50,则n = 5,min = 10,max = 50
使用6个桶,每个桶的大小为(max - min) / n = 8
,具体范围如下:
[10, 18), [18, 26), [26, 34), [34, 42), [42, 50), [50, 58)
则10在0号桶,25在1号桶,34在3号桶,43在4号桶,50在5号桶
为什么最大差值不会出现在桶内,如果某个桶有多个值,那么其桶内最大差值将小于桶的大小,又因为首尾之间必有空桶存在(鸽巢原理,n个数放入n+1个桶,则必有一个桶为空),而横跨至少一个空桶的差值一定比桶内差值大,所以最大差值不会出现在桶内。
Time complexity :
O
(
n
)
O(n)
O(n)
Space complexity :
O
(
n
)
O(n)
O(n)
Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 桶排序
* @author wylu
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] strs = br.readLine().split(" ");
n = strs.length;
int[] a = new int[n];
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(strs[i]);
if (a[i] < min) min = a[i];
if (a[i] > max) max = a[i];
}
if (n < 2 || max == min) {
System.out.println(0);
return;
}
//每个桶是否有值
boolean[] hasNum = new boolean[n + 1];
//每个桶的最小值
int[] low = new int[n + 1];
//每个桶的最大值
int[] high = new int[n + 1];
for (int num : a) {
int idx = getBucketIndex(num, n, max, min);
low[idx] = hasNum[idx] ? Math.min(low[idx], num) : num;
high[idx] = hasNum[idx] ? Math.max(high[idx], num) : num;
hasNum[idx] = true;
}
int res = 0, lastMax = high[0];
for (int i = 1; i <= n; i++) {
if (hasNum[i]) {
res = Math.max(res, low[i] - lastMax);
lastMax = high[i];
}
}
System.out.println(res);
}
private static int getBucketIndex(long num, long n, long max, long min) {
return (int) ((num - min) * n / (max - min));
}
}