Shortest Word Distance
Problem Descriptionβ
Visit LeetCode for the full problem description.
Solutionsβ
Solution 1: C# (Best: 97 ms)β
| Metric | Value |
|---|---|
| Runtime | 97 ms |
| Memory | 38.8 MB |
| Date | 2022-01-28 |
Solution
public class Solution {
public int ShortestDistance(string[] wordsDict, string word1, string word2) {
int min = Int32.MaxValue, index1 = -1, index2 = -1;
for(int i=0;i<wordsDict.Length;i++)
{
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;
}
}
π 1 more C# submission(s)
Submission (2022-01-27) β 122 ms, 38.7 MBβ
public class Solution {
public int ShortestDistance(string[] wordsDict, string word1, string word2) {
int min = Int32.MaxValue, index1 = -1, index2 = -1;
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;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | To be analyzed | To be analyzed |