Shortest Word Distance III
Problem Descriptionβ
Visit LeetCode for the full problem description.
Solutionsβ
Solution 1: C# (Best: 176 ms)β
| Metric | Value |
|---|---|
| Runtime | 176 ms |
| Memory | 52.5 MB |
| Date | 2022-01-28 |
Solution
public class Solution {
public int ShortestWordDistance(string[] wordsDict, string word1, string word2) {
int min = Int32.MaxValue, index1 = -1, index2 = -1, prev = -1;
if(word1.Equals(word2))
{
for(int i=0;i<wordsDict.Length;i++)
{
if(wordsDict[i].Equals(word1))
{
if(prev != -1) min = Math.Min(min, i-prev);
prev = i;
}
}
}
else {
for(int i=0;i<wordsDict.Length;i++)
{
if(wordsDict[i].Equals(word1))
{
index1 = i;
if(index2 != -1) min = Math.Min(min, index1-index2);
}
if(wordsDict[i].Equals(word2))
{
index2 = i;
if(index1 != -1) min = Math.Min(min, index2-index1);
}
}
}
return min;
}
}
π 1 more C# submission(s)
Submission (2022-01-28) β 180 ms, 52.1 MBβ
public class Solution {
public int ShortestWordDistance(string[] wordsDict, string word1, string word2) {
int min = Int32.MaxValue, index1 = -1, index2 = -1, prev = -1;
bool isSame = word1.Equals(word2);
for (int i = 0; i < wordsDict.Length; i++)
{
if (isSame)
{
if (wordsDict[i].Equals(word1))
{
if (prev != -1) min = Math.Min(min, i - prev);
prev = i;
}
}
else
{
if (wordsDict[i].Equals(word1))
{
index1 = i;
}
if (wordsDict[i].Equals(word2))
{
index2 = i;
}
if (index1 != -1 && index2 != -1) min = Math.Min(min, Math.Abs(index1 - index2));
}
}
return min;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | To be analyzed | To be analyzed |