-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2515.cpp
More file actions
30 lines (28 loc) · 962 Bytes
/
2515.cpp
File metadata and controls
30 lines (28 loc) · 962 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
25
26
27
28
29
30
class Solution {
public:
int closetTarget(vector<string>& words, string target, int startIndex) {
unordered_map<string, vector<int>> mp;
int n = words.size();
for (int i = 0; i < n; ++i) mp[words[i]].push_back(i);
if (mp.find(target) == mp.end()) return -1;
int ans = INT_MAX;
for (auto& position : mp[target]) {
ans = min(ans, abs(startIndex - position));
ans = min(ans, abs(startIndex + n - position));
ans = min(ans, abs(position + n - startIndex));
}
return ans;
}
};
class Solution {
public:
int closestTarget(vector<string>& words, string target, int startIndex) {
int n = words.size();
int res = INT_MAX;
for (int i = 0; i < n; ++i) {
int idx = (i + startIndex) % n;
if (words[idx] == target) res = min(res, min(i, n - i));
}
return res == INT_MAX ? -1 : res;
}
};