TGViewer
C# | LeetCode C# | LeetCode @easy_c_sharp_task · 3.17K subscribers
Post #1461 292
Задача: 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.

😎 Решение:
using System;
using System.Collections.Generic;

public class Solution {
public int ShortestWordDistance(string[] wordsDict, string word1, string word2) {
List<int> indices1 = new List<int>();
List<int> indices2 = new List<int>();
for (int i = 0; i < wordsDict.Length; i++) {
if (wordsDict[i] == word1) {
indices1.Add(i);
}
if (wordsDict[i] == word2) {
indices2.Add(i);
}
}

int shortestDistance = int.MaxValue;
foreach (int index in indices1) {
int x = indices2.BinarySearch(index);
if (x < 0) {
x = ~x;
}
if (x < indices2.Count) {
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_c_sharp_task
  1. Oct 16, 2026Задача: 1416. Restore The Array Сложность: hard Программа должна была напечатать массив це…
  2. Oct 15, 2026Задача: 217. Contains Duplicate Сложность: easy Дан массив целых чисел nums. Верните true,…
  3. Oct 15, 2026Задача: 759. Employee Free Time Сложность: hard Нам дан список schedule of employees, кото…
  4. Oct 14, 2026Задача: 583. Delete Operation for Two Strings Сложность: medium Даны две строки word1 и wo…
  5. Oct 14, 2026Задача: 1252. Cells with Odd Values in a Matrix Сложность: easy Имеется матрица m x n, кот…
  6. Oct 13, 2026Задача: 325. Maximum Size Subarray Sum Equals k Сложность: medium Дан целочисленный массив…
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 →