Skip to content

Commit a70e54a

Browse files
committed
244 solved.
1 parent 1abef92 commit a70e54a

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
cmake_minimum_required(VERSION 3.13)
2+
project(cpp_0244)
3+
4+
set(CMAKE_CXX_STANDARD 11)
5+
6+
add_executable(cpp_0244 main.cpp)
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/// Source : https://leetcode.com/problems/shortest-word-distance-ii/
2+
/// Author : liuyubobobo
3+
/// Time : 2019-02-13
4+
5+
#include <iostream>
6+
#include <vector>
7+
#include <unordered_map>
8+
9+
using namespace std;
10+
11+
12+
/// Search in two sorted index array
13+
/// Time Complexity: init: O(n)
14+
/// search: O(n)
15+
/// Space Complexity: O(n)
16+
class WordDistance {
17+
18+
private:
19+
unordered_map<string, vector<int>> pos;
20+
21+
public:
22+
WordDistance(vector<string> words) {
23+
for (int i = 0; i < words.size(); i++)
24+
pos[words[i]].push_back(i);
25+
}
26+
27+
int shortest(string word1, string word2) {
28+
29+
vector<int>& vec1 = pos[word1];
30+
vector<int>& vec2 = pos[word2];
31+
32+
int i1 = 0, i2 = 0;
33+
int res = abs(vec1[i1] - vec2[i2]);
34+
while(i1 < vec1.size() && i2 < vec2.size()){
35+
res = min(res, abs(vec1[i1] - vec2[i2]));
36+
if(vec1[i1] < vec2[i2]) i1 ++;
37+
else i2 ++;
38+
}
39+
40+
return res;
41+
}
42+
};
43+
44+
45+
int main() {
46+
47+
return 0;
48+
}

readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,7 @@ email: [liuyubobobo@gmail.com](mailto:liuyubobobo@gmail.com)
250250
| | | | | | |
251251
| 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram/description/) | [solution](https://leetcode.com/problems/valid-anagram/solution/) | [C++](0242-Valid-Anagram/cpp-0242/) | | |
252252
| 243 | [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | [solution](https://leetcode.com/problems/shortest-word-distance/solution/) | [C++](0243-Shortest-Word-Distance/cpp-0243/) | | |
253+
| 244 | [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/) | [solution](https://leetcode.com/problems/shortest-word-distance-ii/solution/) | [C++](0244-Shortest-Word-Distance-II/cpp-0244/) | | |
253254
| | | | | | |
254255
| 249 | [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/description/) | [] | [C++](0249-Group-Shifted-Strings/cpp-0249/) | | |
255256
| 250 | [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees/description/) | [] | [C++](0250-Count-Univalue-Subtrees/cpp-0250/) | | |

0 commit comments

Comments
 (0)