[LeetCode] 243. Shortest Word Distance_Easy
2018-08-16 12:08 Johnson_强生仔仔 阅读(194) 评论(0) 编辑 收藏 举报Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
Input: word1 =“coding”
, word2 =“practice”
Output: 3
Input: word1 ="makes"
, word2 ="coding"
Output: 1
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
基本思路为O(n^2) 就是每次扫了word1之后再扫word2.
Imporve 思路为O(n), 也就是每次找到两个相应的最近的点, 我们就跟ans比较一下, ans的初始化为len(words)
Code
class Solution: def shortestDistance(self, words, word1,word2): point1, point2, ans, words = None, None, len(words), [0] + words # 有[0]是为了方便edge case, 我们直接用point1 and point2来判断, 否则point1 or point2 == 0 的时候会影响 for i in range(1, len(words)): if words[i] == word1: point1 = i if words[i] == word2: point2 = i if point1 and point2: ans = min(ans, abs(point1 - point2)) return ans