Leetcode 243: Shortest Word Distance

问题描述:
Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.
找两个元素在数组中的最短距离

思路:
用Hashmap记录相关元素(跳过不考虑不是word1或word2的)及其对应的出现位置,若此刻两个元素在map中都有,则我们计算它们的距离差的绝对值并与上一轮的值比较取较小者,这样遍历完整个数组,我们得到的距离就是最小距离。

关注限制条件:
Constraints:
1 <= wordsDict.length <= 3 * 104
1 <= wordsDict[i].length <= 10
wordsDict[i] consists of lowercase English letters.
word1 and word2 are in wordsDict.
word1 != word2

代码一遍过:

class Solution {
    public int shortestDistance(String[] wordsDict, String word1, String word2) {
        Map<String, Integer> map = new HashMap<>();
        int minDist = Integer.MAX_VALUE;
        for (int i=0; i<wordsDict.length; i++){
            if ((wordsDict[i].equals(word1)) || (wordsDict[i].equals(word2))){
                if (wordsDict[i].equals(word1)) map.put(word1, i);
                else map.put(word2,i);
                if (map.containsKey(word1) && map.containsKey(word2)){
                    minDist = Math.min(minDist, Math.abs(map.get(word1)-map.get(word2)));
                }
            }
        }
        return minDist;
    }
}

时间复杂度: O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值