力扣每日一题2022-05-27中等题:单词距离


题目描述

单词距离


思路

遍历

最直观的做法为遍历数组words,对于数组中的每个word1,遍历数组words找到每个word2并计算距离,时间复杂度为O(n^2)。这个解法有优化空间。可以从左往右遍历words,当遍历到word1时,如果已遍历的单词中存在word2,为计算最短距离,可以取最后一个已经遍历到的word2所在的下标来计算距离。同理,遍历到word2时,则取最后一个word1的下标计算距离。
上述最后一个已经遍历到的word1和word2可以分别用index1和index2表示,则节省了使用数组存储下标位置的空间。初始化两个下标都为-1,如果遍历到word1则更新index1,如果遍历到word2,更新index2;如果index1和index2都大于0,则计算两个index的差的绝对值,用这个绝对值更新最短距离。遍历结束返回结果即可。

Python实现
class Solution:
    def findClosest(self, words: List[str], word1: str, word2: str) -> int:
        ans, idx1, idx2 = len(words), -1, -1
        for i, word in enumerate(words):
            if word == word1:
                idx1 = i
            elif word == word2:
                idx2 = i
            if idx1 >= 0 and idx2 >= 0:
                ans = min(ans, abs(idx2-idx1))
        return ans
Java实现
class Solution {
    public int findClosest(String[] words, String word1, String word2) {
        int ans = words.length, idx1 = -1, idx2 = -1;
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            if (word.equals(word1)) {
                idx1 = i;
            } else if (word.equals(word2)) {
                idx2 = i;
            }
            if (idx1 >= 0 && idx2 >= 0) {
                ans = Math.min(ans, Math.abs(idx2-idx1));
            }
        }
        return ans;
    }
}
C++实现
class Solution {
public:
    int findClosest(vector<string>& words, string word1, string word2) {
        int length = words.size();
        int ans = length, idx1 = -1, idx2 = -1;
        for (int i = 0; i < length; i++) {
            string word = words[i];
            if (word == word1) {
                idx1 = i;
            } else if (word == word2) {
                idx2 = i;
            }
            if (idx1 >= 0 && idx2 >= 0) {
                ans = min(ans, abs(idx2 - idx1));
            }
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值