forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinimumDistanceToTheTargetElement.java
34 lines (31 loc) · 1.25 KB
/
MinimumDistanceToTheTargetElement.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
import java.util.ArrayList;
import java.util.List;
public class MinimumDistanceToTheTargetElement {
public int getMinDistance(int[] nums, int target, int start) {
final List<Integer> indexes = getIndexes(nums, target);
final int position = search(indexes, start);
if (position >= indexes.size()) return start - indexes.get(position - 1);
if (indexes.get(position) == start) return 0;
if (position == 0) return indexes.get(position) - start;
return Math.min(indexes.get(position) - start, start - indexes.get(position - 1));
}
private List<Integer> getIndexes(int[] array, int target){
final List<Integer> indexes = new ArrayList<>();
for (int index = 0 ; index < array.length ; index++) {
if (array[index] == target) {
indexes.add(index);
}
}
return indexes;
}
private int search(List<Integer> array, int x) {
int left = 0, right = array.size() - 1, middle;
while (left <= right) {
middle = left + (right - left) / 2;
if (array.get(middle) == x) return middle;
else if (array.get(middle) > x) right = middle - 1;
else left = middle + 1;
}
return left;
}
}