Leetcode--164. 最大间距
发布日期:2021-04-30 21:05:26
浏览次数:114
分类:精选文章
本文共 2834 字,大约阅读时间需要 9 分钟。
?????????????????????????????????????????????????????????????????????????????????
????
???????????????????????????????????????
??????????
- ????
t???(max - min) / (n - 1)???n??????????n - 1??????? - ??
(max - min)???(n - 1)??????????????????????????????? - ????
sum???1 + (max - min) / t???????????????????????
????????????????ArrayList????????????????
???????????????????????????????????????????????????????
????????????????????????????????????????
????
import java.util.ArrayList;class Tong { int max; int min; Tong() { max = Integer.MIN_VALUE; min = Integer.MAX_VALUE; }}public class Solution { public int maximumGap(int[] nums) { if (nums.length < 2) { return 0; } int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for (int num : nums) { max = Math.max(max, num); min = Math.min(min, num); } int n = nums.length; int t = (max - min) / (n - 1); if (t == 0) { t = 1; } int sum = 1 + (max - min) / t; ArrayList tong = new ArrayList<>(); for (int i = 0; i < sum; i++) { tong.add(new Tong()); } for (int num : nums) { int x = (num - min) / t; if (x >= 0 && x < sum) { Tong bucket = tong.get(x); bucket.max = Math.max(bucket.max, num); bucket.min = Math.min(bucket.min, num); } } int maxGap = 0; int currentMin = Integer.MAX_VALUE; int currentMax = Integer.MIN_VALUE; for (int i = 0; i < sum; i++) { Tong bucket = tong.get(i); if (bucket.max == Integer.MIN_VALUE) { continue; } if (i == 0) { currentMin = bucket.min; currentMax = bucket.max; } else { if (currentMin == Integer.MAX_VALUE) { currentMin = bucket.min; currentMax = bucket.max; } else { int gap = currentMax - currentMin; if (gap > maxGap) { maxGap = gap; } if (bucket.min < currentMin) { currentMin = bucket.min; } if (bucket.max > currentMax) { currentMax = bucket.max; } } } } return maxGap; }} ????
?????????????????????2????????0??????????????????
??????????????????????????? t ??? sum??? t ???1?????0???
???????? ArrayList ?????????????????
??????????????????????????????????????
????????????????????????????????????
????????O(n)???????O(n)?????????????????????
发表评论
最新留言
很好
[***.229.124.182]2026年06月05日 01时22分31秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!