From d432178d1ea67654287b21ac640fffdb8c0521c4 Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Fri, 27 May 2022 23:30:31 +0800 Subject: [PATCH] add: 220527-CN [cpp] --- cpp/2205/220527-CN.cpp | 25 +++++++++++++++++++++++++ cpp/2205/CMakeLists.txt | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 cpp/2205/220527-CN.cpp diff --git a/cpp/2205/220527-CN.cpp b/cpp/2205/220527-CN.cpp new file mode 100644 index 0000000..57a5fd2 --- /dev/null +++ b/cpp/2205/220527-CN.cpp @@ -0,0 +1,25 @@ +#include +#include + +/** + * 面试题 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& 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; + } +}; diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index d0312df..2a5d483 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2205 220525-CN.cpp) +ADD_EXECUTABLE(2205 220527-CN.cpp)