-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathsolution.cpp
More file actions
35 lines (29 loc) · 884 Bytes
/
solution.cpp
File metadata and controls
35 lines (29 loc) · 884 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
31
32
33
34
35
class Solution
{
public:
int minimumDistance(vector<int> &nums)
{
unordered_map<int, vector<int>> positions;
// Store all indices for each value
for (int i = 0; i < nums.size(); i++)
{
positions[nums[i]].push_back(i);
}
int ans = INT_MAX;
// Check every value's index list
for (auto &entry : positions)
{
vector<int> &idx = entry.second;
// Need at least 3 occurrences
if (idx.size() < 3)
continue;
// Check every consecutive group of 3 indices
for (int i = 0; i + 2 < idx.size(); i++)
{
int distance = 2 * (idx[i + 2] - idx[i]);
ans = min(ans, distance);
}
}
return (ans == INT_MAX) ? -1 : ans;
}
};