TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.43K subscribers
Post #1623 745
Задача: 245. Shortest Word Distance II
Сложность: medium

Дан массив строк wordsDict и две строки word1 и word2, которые уже существуют в массиве. Верните наименьшее расстояние между вхождениями этих двух слов в списке.

Обратите внимание, что word1 и word2 могут быть одинаковыми. Гарантируется, что они представляют собой два отдельных слова в списке.

Пример:
Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output: 1


👨‍💻 Алгоритм:

1⃣Переберите список wordsDict и сохраните индексы слова word1 в список indices1 и индексы слова word2 в список indices2. Инициализируйте переменную shortestDistance = INT_MAX.

2⃣Переберите индексы в списке indices1 и для каждого индекса найдите верхнюю границу в списке indices2, используя бинарный поиск, и сохраните этот индекс в переменную x. Рассмотрите индексы indices2[x] и indices2[x - 1], обновляя shortestDistance, если индексы не совпадают.

3⃣Верните значение переменной shortestDistance.

😎 Решение:
import java.util.*;

class Solution {
public int shortestWordDistance(String[] wordsDict, String word1, String word2) {
List<Integer> indices1 = new ArrayList<>();
List<Integer> indices2 = new ArrayList<>();
for (int i = 0; i < wordsDict.length; i++) {
if (wordsDict[i].equals(word1)) {
indices1.add(i);
}
if (wordsDict[i].equals(word2)) {
indices2.add(i);
}
}

int shortestDistance = Integer.MAX_VALUE;
for (int index : indices1) {
int x = Collections.binarySearch(indices2, index);
if (x < 0) {
x = -x - 1;
}
if (x < indices2.size()) {
shortestDistance = Math.min(shortestDistance, indices2.get(x) - index);
}
if (x > 0 && !indices2.get(x - 1).equals(index)) {
shortestDistance = Math.min(shortestDistance, index - indices2.get(x - 1));
}
}
return shortestDistance;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_java_task
  1. Oct 17, 2026Post #2303
  2. Oct 17, 2026Задача: 1431. Kids With the Greatest Number of Candies Сложность: easy Дано n детей с конф…
  3. Oct 16, 2026Задача: 735. Asteroid Collision Сложность: medium Нам дан массив asteroids, состоящий из ц…
  4. Oct 16, 2026Post #2300
  5. Oct 15, 2026Задача: 229. Majority Element II Сложность: medium Дан массив целых чисел размера n, найди…
  6. Oct 14, 2026Задача: 1332. Remove Palindromic Subsequences Сложность: easy Вам дана строка s, состоящая…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →