forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
48 lines (35 loc) · 1002 Bytes
/
main.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
/// Source : https://leetcode.com/problems/shortest-word-distance-ii/
/// Author : liuyubobobo
/// Time : 2019-02-13
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/// Search in two sorted index array
/// Time Complexity: init: O(n)
/// search: O(n)
/// Space Complexity: O(n)
class WordDistance {
private:
unordered_map<string, vector<int>> pos;
public:
WordDistance(vector<string> words) {
for (int i = 0; i < words.size(); i++)
pos[words[i]].push_back(i);
}
int shortest(string word1, string word2) {
vector<int>& vec1 = pos[word1];
vector<int>& vec2 = pos[word2];
int i1 = 0, i2 = 0;
int res = abs(vec1[i1] - vec2[i2]);
while(i1 < vec1.size() && i2 < vec2.size()){
res = min(res, abs(vec1[i1] - vec2[i2]));
if(vec1[i1] < vec2[i2]) i1 ++;
else i2 ++;
}
return res;
}
};
int main() {
return 0;
}