243. Shortest Word Distance 最短的单词index之差

[抄题]:

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.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不知道用什么数据结构指定index

[一句话思路]:

指定index只需要成-1然后遍历就行

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 头一次见:必须在p1 p2都摆脱初始值-1的时候,才能比较,否则一直为0

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

必须在p1 p2都摆脱初始值-1的时候,才能比较,否则一直为0

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

字符串判断相等用的是equals,你没记错

[关键模板化代码]:

[其他解法]:

[Follow Up]:

244. Shortest Word Distance II 多次调用:hashmap多次取

3:可重复:用数学

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        //cc
        if (words == null || words.length == 0) {
            return 0;
        }
        
        //ini
        int p1 = -1, p2 = -1, min = Integer.MAX_VALUE;
        
        //for loop, renew p1 p2, compare
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                p1 = i;
            }
            
            if (words[i].equals(word2)) {
                p2 = i;
            }
            
            if (p1 != -1 && p2 != -1) {
                min = Math.min(min, Math.abs(p2 - p1));
            }
        }

        //return
        return min;
    }
}
View Code

 

转载于:https://www.cnblogs.com/immiao0319/p/8898076.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值