-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path164.maximum-gap.java
More file actions
53 lines (51 loc) · 1.67 KB
/
164.maximum-gap.java
File metadata and controls
53 lines (51 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public int maximumGap(int[] nums) {
int n = nums.length;
if (n<2) return 0;
int max = nums[0],min = nums[0];
for (int x:nums) {
max = Math.max(max,x);
min = Math.min(min,x);
}
int[] xmin = new int[nums.length];
int[] xmax = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
xmin[i]=-1;
xmax[i]=-1;
}
int gap = (max-min)/(nums.length-1)+1;
if (gap==0) return 0;
for (int x:nums) {
int index = (x-min)/gap;
if (xmin[index]==-1){
xmin[index]=x;
xmax[index]=x;
}else {
xmin[index] = Math.min(xmin[index],x);
xmax[index] = Math.max(xmax[index],x);
}
}
int maxindex = 0, minindex = 1, result = 0;
while(maxindex<nums.length){
if (xmax[maxindex]==-1){
maxindex++;
continue;
}else {
result = Math.max(xmax[maxindex]-xmin[maxindex],result);
minindex=maxindex+1;
while(minindex<nums.length){
if (xmin[minindex]==-1){
minindex++;
continue;
}else {
result = Math.max(xmax[minindex]-xmin[minindex],result);
result = Math.max(xmin[minindex]-xmax[maxindex],result);
maxindex=minindex;
break;
}
}
maxindex=minindex;
}
}
return result;
}}