首页 技术 正文
技术 2022年11月6日
0 收藏 687 点赞 938 浏览 760 个字

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
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,996
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,510
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,353
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,137
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848