245. Shortest Word Distance III
2020-12-03 本文已影响0人
Ysgc
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
word1 and word2 may be the same and they represent two individual words in the list.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Input: word1 = “makes”, word2 = “coding”
Output: 1
Input: word1 = "makes", word2 = "makes"
Output: 3
Note:
You may assume word1 and word2 are both in the list.
我的答案:感觉这道题挺无聊的,就是243再加一个if的情况
class Solution {
public:
int shortestWordDistance(vector<string>& words, string word1, string word2) {
int ans = INT_MAX;
int len = words.size();
if (word1 == word2) {
int last = INT_MIN;
for (int i=0; i<len; ++i) {
if (words[i] == word1) {
if (last != INT_MIN)
ans = min(ans, abs(i-last));
last = i;
}
}
}
else {
int last1 = INT_MIN;
int last2 = INT_MIN;
for (int i=0; i<len; ++i) {
// cout << ans << " - " << abs(last1-last2)) << endl;
if (words[i] == word1 or words[i] == word2) {
if (words[i] == word1)
last1 = i;
if (words[i] == word2)
last2 = i;
if (last1 != INT_MIN and last2 != INT_MIN)
ans = min(ans, abs(last1-last2));
}
}
}
return ans;
}
};
Runtime: 12 ms, faster than 97.08% of C++ online submissions for Shortest Word Distance III.
Memory Usage: 12.3 MB, less than 62.57% of C++ online submissions for Shortest Word Distance III.