- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1182.java
52 lines (48 loc) · 1.78 KB
/
_1182.java
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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
publicclass_1182 {
publicstaticclassSolution1 {
publicList<Integer> shortestDistanceColor(int[] colors, int[][] queries) {
Map<Integer, List<Integer>> map = buildMap(colors);
List<Integer> result = newArrayList<>();
for (int[] query : queries) {
result.add(binarySearch(query[0], map.get(query[1])));
}
returnresult;
}
privateIntegerbinarySearch(intindex, List<Integer> indices) {
if (indices == null) {
return -1;
}
intleft = 0;
intright = indices.size() - 1;
intminDistance = Integer.MAX_VALUE;
while (left <= right) {
intmid = left + (right - left) / 2;
if (indices.get(mid) == index) {
return0;
} elseif (indices.get(mid) > index) {
minDistance = Math.min(minDistance, indices.get(mid) - index);
right = mid - 1;
} else {
minDistance = Math.min(minDistance, index - indices.get(mid));
left = mid + 1;
}
}
returnminDistance;
}
privateMap<Integer, List<Integer>> buildMap(int[] colors) {
Map<Integer, List<Integer>> map = newHashMap<>();
for (inti = 0; i < colors.length; i++) {
if (!map.containsKey(colors[i])) {
map.put(colors[i], newArrayList<>());
}
map.get(colors[i]).add(i);
}
returnmap;
}
}
}