-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathsolution.java
More file actions
24 lines (20 loc) · 771 Bytes
/
solution.java
File metadata and controls
24 lines (20 loc) · 771 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int closestTarget(String[] words, String target, int startIndex) {
int n = words.length;
int ans = Integer.MAX_VALUE;
// Check every index in the array
for (int i = 0; i < n; i++) {
// If current word matches target
if (words[i].equals(target)) {
// Normal distance between indices
int diff = Math.abs(i - startIndex);
// Circular distance
int circularDist = n - diff;
// Update minimum answer
ans = Math.min(ans, Math.min(diff, circularDist));
}
}
// If target does not exist
return ans == Integer.MAX_VALUE ? -1 : ans;
}
}