leetcode 243

原题是:

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 = ["practice", "makes", "perfect", "coding", "makes"].

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.

代码是:

class Solution(object):
    def shortestDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        size = len(words)
        index1, index2 = size, size
        ans = size
    
        for i in xrange(size):
            if words[i] == word1:
                index1 = i
                ans = min(ans, abs(index1-index2))
            elif words[i] == word2:
                index2 = i
                ans = min(ans, abs(index1-index2))
        
        return ans

这一题学到的点是:

1. python 中range 和xrange的区别

leetcode 243_第1张图片
Screen Shot 2017-10-03 at 6.58.44 AM.png
leetcode 243_第2张图片
Screen Shot 2017-10-03 at 6.59.06 AM.png

2.

之前的死掉的思路是,如果锁定一个符合word1的字符串,然后去就近寻找word2的字符串,这样是N的二次方的时间复杂度。

学习,体会这种代码中的解决问题的方式,和思路。

你可能感兴趣的:(leetcode 243)