forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_2515.java
31 lines (30 loc) · 1.1 KB
/
_2515.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
package com.fishercoder.solutions;
public class _2515 {
public static class Solution1 {
public int closetTarget(String[] words, String target, int startIndex) {
int ans = words.length;
if (words[startIndex].equals(target)) {
return 0;
}
//move forward
int forwardSteps = 1;
for (int i = (startIndex + 1) % words.length; i != startIndex; i = ((i + 1) % words.length)) {
if (words[i].equals(target)) {
ans = Math.min(ans, forwardSteps);
break;
}
forwardSteps++;
}
//move backward
int backwardSteps = 1;
for (int i = (startIndex - 1 + words.length) % words.length; i != startIndex; i = ((i - 1 + words.length) % words.length)) {
if (words[i].equals(target)) {
ans = Math.min(ans, backwardSteps);
break;
}
backwardSteps++;
}
return ans == words.length ? -1 : ans;
}
}
}