题解 | #数组排序之后相邻数的最大差值#
数组排序之后相邻数的最大差值
http://www.nowcoder.com/practice/2ccf4314d6fc443cb6b6c2372eb6a8f7
import java.util.Scanner; public class Main { public static int maxGap(int[] nums) { if (nums == null || nums.length < 2) { return 0; } int len = nums.length; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i < len; i++) { min = Math.min(min, nums[i]); max = Math.max(max, nums[i]); } if (min == max) { return 0; } boolean[] hasNum = new boolean[len + 1]; //判断该序号桶中是否存在数据 int[] maxs = new int[len + 1]; //记录每一个桶里面的最大值与最小值 int[] mins = new int[len + 1]; int bid = 0; for (int i = 0; i < len; i++) { bid = bucket(nums[i], len, min, max); //计算桶号 maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], nums[i]) : nums[i]; mins[bid] = hasNum[bid] ? Math.min(mins[bid], nums[i]) : nums[i]; hasNum[bid] = true; } int res = 0; int lastMax = maxs[0]; //前一个非空桶中的最大值[桶的序号0-N] int i = 1; for (; i <= len; i++) { if (hasNum[i]) { res = Math.max(res, mins[i] - lastMax); lastMax = maxs[i]; } } return res; } //计算数据应该放的桶的位置 public static int bucket(long num, long len, long min, long max) { //每一个桶的范围(max-min)/len return (int) ((num - min) * len / (max - min)); } public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int[] nums=new int[n]; for (int i = 0; i <n ; i++) { nums[i]=in.nextInt(); } int res=maxGap(nums); System.out.println(res); } }