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的区别

Screen Shot 2017-10-03 at 6.58.44 AM.png
Screen Shot 2017-10-03 at 6.59.06 AM.png

2.

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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容