TGViewer
JavaScript | LeetCode JavaScript | LeetCode @easy_frontend_task · 8.32K subscribers
Post #2281 661
Задача: 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.

😎 Решение:
class Solution {
shortestWordDistance(wordsDict, word1, word2) {
const indices1 = [];
const indices2 = [];
wordsDict.forEach((word, i) => {
if (word === word1) {
indices1.push(i);
}
if (word === word2) {
indices2.push(i);
}
});

let shortestDistance = Infinity;
indices1.forEach(index => {
const x = indices2.findIndex(i => i > index);
if (x !== -1) {
shortestDistance = Math.min(shortestDistance, indices2[x] - index);
}
if (x > 0 && indices2[x - 1] !== index) {
shortestDistance = Math.min(shortestDistance, index - indices2[x - 1]);
}
});
return shortestDistance;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_frontend_task
  1. Oct 11, 2026Задача: 651. 4 Keys Keyboard Сложность: medium Представьте, что у вас есть специальная кла…
  2. Oct 9, 2026Задача: 1054. Distant Barcodes Сложность: medium На складе имеется ряд штрих-кодов, где i-…
  3. Oct 9, 2026Задача: 1237. Find Positive Integer Solution for a Given Equation Сложность: medium Если д…
  4. Oct 8, 2026Задача: №19. Remove Nth Node From End of List Сложность: medium Дан связанный список и чис…
  5. Oct 7, 2026Задача: 1057. Campus Bikes Сложность: medium В городке, изображенном на плоскости X-Y, ест…
  6. Oct 7, 2026🔥 Скрытые вакансии с удаленной работой для Frontend разработчика, которые нигде больше не…
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 →