diff --git a/lcci/17.11.Find Closest/README.md b/lcci/17.11.Find Closest/README.md index 965043a6e246a..ed038d504c4a8 100644 --- a/lcci/17.11.Find Closest/README.md +++ b/lcci/17.11.Find Closest/README.md @@ -137,6 +137,28 @@ impl Solution { } ``` +```swift +class Solution { + func findClosest(_ words: [String], _ word1: String, _ word2: String) -> Int { + let inf = Int.max / 2 + var i = inf + var j = -inf + var ans = inf + + for (k, word) in words.enumerated() { + if word == word1 { + i = k + } else if word == word2 { + j = k + } + ans = min(ans, abs(i - j)) + } + + return ans + } +} +``` + <!-- tabs:end --> ### 方法二:哈希表 + 双指针 diff --git a/lcci/17.11.Find Closest/README_EN.md b/lcci/17.11.Find Closest/README_EN.md index 3b23d9ab471cb..885613ba20479 100644 --- a/lcci/17.11.Find Closest/README_EN.md +++ b/lcci/17.11.Find Closest/README_EN.md @@ -139,6 +139,28 @@ impl Solution { } ``` +```swift +class Solution { + func findClosest(_ words: [String], _ word1: String, _ word2: String) -> Int { + let inf = Int.max / 2 + var i = inf + var j = -inf + var ans = inf + + for (k, word) in words.enumerated() { + if word == word1 { + i = k + } else if word == word2 { + j = k + } + ans = min(ans, abs(i - j)) + } + + return ans + } +} +``` + <!-- tabs:end --> ### Solution 2: Hash Table + Two Pointers diff --git a/lcci/17.11.Find Closest/Solution.swift b/lcci/17.11.Find Closest/Solution.swift new file mode 100644 index 0000000000000..b4d89340ecca3 --- /dev/null +++ b/lcci/17.11.Find Closest/Solution.swift @@ -0,0 +1,19 @@ +class Solution { + func findClosest(_ words: [String], _ word1: String, _ word2: String) -> Int { + let inf = Int.max / 2 + var i = inf + var j = -inf + var ans = inf + + for (k, word) in words.enumerated() { + if word == word1 { + i = k + } else if word == word2 { + j = k + } + ans = min(ans, abs(i - j)) + } + + return ans + } +}