Leetcode: Day 126, #243 #244 Shortest Word Distance, Shortest Word Distance II
Day 126, #243 #244 Shortest Word Distance, Shortest Word Distance II Shortest Word Distance Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. For example, . Note: ---------------------------------------------------------------------------- class Solution { public: int shortestDistance(vector
& words, string word1, string word2) { int shortest = words.size(); int pos1 = -words.size(), pos2 = -words.size(); for (int i = 0; i < words.size(); i++) { if (words[i] == word1) { pos1 = i; shortest = min(shortest,pos1 - pos2); } if (words[i] == word2) { pos2 = i; shortest = min(shortest,pos2 - pos1); } } return shortest; } }; Shortest Word Distance II This is a follow up of Shortest Word Distance . The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?
Read full article from Leetcode: Day 126, #243 #244 Shortest Word Distance, Shortest Word Distance II
No comments:
Post a Comment