-
Notifications
You must be signed in to change notification settings - Fork 28
/
Shortest_Word_Distance_III.cpp
68 lines (62 loc) · 2.21 KB
/
Shortest_Word_Distance_III.cpp
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Solution {
public:
int lowerBound(int left, int right, const int value, vector<int> const& container) {
if(left >= right) {
return left;
}
int mid = left + (right - left) / 2;
if(value <= container[mid]) {
return lowerBound(left, mid, value, container);
} else if(value > container[mid]) {
return lowerBound(mid + 1, right, value, container);
}
}
int upperBound(int left, int right, const int value, vector<int> const& container) {
if(left >= right) {
return left;
}
int mid = left + (right - left) / 2;
if(value < container[mid]) {
return upperBound(left, mid, value, container);
} else if(value >= container[mid]) {
return upperBound(mid + 1, right, value, container);
}
}
int shortestWordDistance(vector<string>& words, string word1, string word2) {
vector<vector<int> > pos(2, vector<int>());
for(int i = 0; i < words.size(); ++i) {
if(words[i] == word1) {
pos[0].push_back(i);
} else if(words[i] == word2) {
pos[1].push_back(i);
}
}
int n = pos[0].size();
int m = pos[1].size();
int ans = INT_MAX;
if(word1 == word2) {
for(int i = 0; i < (int) pos[0].size() - 1; ++i) {
ans = min(ans, pos[0][i + 1] - pos[0][i]);
}
return ans;
}
if(pos[0][n - 1] < pos[1][0]) {
return (pos[1][0] - pos[0][n - 1]);
}
if(pos[0][0] > pos[1][m - 1]) {
return (pos[0][0] - pos[1][m - 1]);
}
for(int i = 0; i < n; ++i) {
int upper = upperBound(0, pos[1].size() - 1, pos[0][i], pos[1]);
ans = min(ans, abs(pos[1][upper] - pos[0][i]));
// int lower = lowerBound(0, pos[1].size() - 1, pos[0][i], pos[1]);
// if(lower > 0) {
// ans = min(ans, abs(pos[1][lower - 1] - pos[0][i]));
// }
if(upper > 0) {
ans = min(ans, abs(pos[1][upper - 1] - pos[0][i]));
}
}
return ans;
}
};