题意:

image.png

解题思路:

  1. 思路:桶排序

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer[] $nums
  4. * @return Integer
  5. */
  6. function maximumGap($nums) {
  7. if (count($nums) <= 1) return 0;
  8. $n = count($nums);
  9. $min = min($nums);
  10. $max = max($nums);
  11. if ($max - $min == 0) {
  12. return 0;
  13. }
  14. $interval = (int)ceil(($max - $min) / ($n - 1));
  15. echo $interval;
  16. $bucketMin = $bucketMax = [];
  17. $bucketMin = array_fill(0, $n - 1, PHP_INT_MAX);
  18. $bucketMax = array_fill(0, $n - 1, -1);
  19. for ($i = 0; $i < count($nums); $i++) {
  20. $index = ($nums[$i] - $min) / $interval;
  21. if ($nums[$i] == $min || $nums[$i] == $max) {
  22. continue;
  23. }
  24. $bucketMin[$index] = min($nums[$i], $bucketMin[$index]);
  25. $bucketMax[$index] = max($nums[$i], $bucketMax[$index]);
  26. }
  27. $maxGap = 0;
  28. $previousMax = $min;
  29. for ($i = 0; $i < $n - 1; $i ++) {
  30. if ($bucketMax[$i] == -1) {
  31. continue;
  32. }
  33. $maxGap = max($bucketMin[$i] - $previousMax, $maxGap);
  34. $previousMax = $bucketMax[$i];
  35. }
  36. $maxGap = max($max - $previousMax, $maxGap);
  37. return $maxGap;
  38. }
  39. function maximumGapOn($nums) {
  40. if (count($nums) < 2) return 0;
  41. sort($nums);
  42. $max = 0;
  43. for ($i = 1; $i < count($nums); $i++) {
  44. $curV = $nums[$i] - $nums[$i - 1];
  45. if ($curV > $max) {
  46. $max = $curV;
  47. }
  48. }
  49. return $max;
  50. }
  51. }