add: 220527-CN [cpp]

This commit is contained in:
Eat-Swap 2022-05-27 23:30:31 +08:00
parent 86c7a0bb11
commit d432178d1e
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 26 additions and 1 deletions

25
cpp/2205/220527-CN.cpp Normal file
View File

@ -0,0 +1,25 @@
#include <string>
#include <vector>
/**
* 17.11. Find Closest LCCI
* You have a large text file containing words. Given any two different words, find the shortest distance (in terms of number of words) between them in the file. If the operation will be repeated many times for the same file (but different pairs of words), can you optimize your solution?
*/
class Solution {
public:
static int findClosest(const std::vector<std::string>& words, const std::string& word1, const std::string& word2) {
int ans = 0x3FFFFFFF, p1 = 0x3FFFFFFF, p2 = 0x3FFFFFFF, cnt = 0;
for (const std::string& s : words) {
if (s == word1) {
p1 = cnt;
ans = std::min(std::abs(p2 - p1), ans);
} else if (s == word2) {
p2 = cnt;
ans = std::min(std::abs(p2 - p1), ans);
}
++cnt;
}
return ans;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2205)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2205 220525-CN.cpp)
ADD_EXECUTABLE(2205 220527-CN.cpp)