Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words =
Assume that words =
["practice", "makes", "perfect", "coding", "makes"]
.
Given word1 =
Given word1 =
“coding”
, word2 = “practice”
, return 3.Given word1 =
"makes"
, word2 = "coding"
, return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int shortestDistance(vector<string>& words, string word1, string word2) { | |
int p1=-1*words.size(), p2=-1*words.size(); | |
int sdist=words.size()-1; | |
for(int i=0; i<words.size(); i++){ | |
if(words[i]==word1){ | |
p1=i; | |
sdist=min(sdist, abs(p2-p1)); | |
continue; | |
} | |
if(words[i]==word2){ | |
p2=i; | |
sdist=min(sdist, abs(p2-p1)); | |
continue; | |
} | |
} | |
return sdist; | |
} | |
}; |
Round 2 solutoin:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int shortestDistance(vector<string>& words, string word1, string word2) { | |
int dist = INT_MAX; | |
int pos1=-words.size(); | |
int pos2=words.size(); | |
for(int i=0; i<words.size(); i++){ | |
pos1 = words[i]==word1? i:pos1; | |
pos2 = words[i]==word2? i:pos2; | |
dist = min(dist, abs(pos2-pos1)); | |
} | |
return dist; | |
} | |
}; |
No comments:
Post a Comment