leetcode:244. 最短单词距离 ii

题目来源

题目描述

请设计一个类,使该类的构造函数能够接收一个单词列表。然后再实现一个方法,该方法能够分别接收两个单词 word1 和 word2,并返回列表中这两个单词之间的最短距离。您的方法将被以不同的参数调用 多次。

示例:

假设 words = [“practice”, “makes”, “perfect”, “coding”, “makes”]

输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = "makes", word2 = "coding"
输出: 1

注意:
你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。

class WordDistance {
public:
    WordDistance(vector<string>& words) {
   
    }

    int shortest(string word1, string word2) {
    
    }

private:

};

题目解析

思路

  • 用一个map来建立每个单词与其所有出现的位置的映射
  • 当需要最短单词距离时,只需要取出该单词在map中映射的数组进行两两比较即可

实现

class WordDistance {
public:
    WordDistance(vector<string>& words) {
        for (int i = 0; i < words.size(); ++i) {
            m[words[i]].push_back(i);
        }
    }

    int shortest(string word1, string word2) {
        int res = INT32_MAX;
        for (int i = 0; i < m[word1].size(); ++i) {
            for (int j = 0; j < m[word2].size(); ++j) {
                res = min(res, abs(m[word1][i] - m[word2][j]));
            }
        }
        return res;
    }

private:
    std::unordered_map<std::string, std::vector<int>> m;
};

优化

  • 用两个指针i和j来指向位置数组中的某个元素,开始时均初始化为0
  • 然后比较位置数组中的数字,将较小的一个指针向后移动一位,直到其中一个数组遍历完成即可
  • 时间复杂度O(M + N),其中M和N为两个单词的长度
class WordDistance {
public:
    WordDistance(vector<string>& words) {
        for (int i = 0; i < words.size(); ++i) {
            m[words[i]].push_back(i);
        }
    }

    int shortest(string word1, string word2) {
        int res = INT32_MAX, i = 0, j = 0;
        while (i < m[word1].size() && j < m[word2].size()){
            res = min(res, abs(m[word1][i] - m[word2][j]));
            m[word1][i] < m[word2][j] ? ++i : ++j;
        }
        return res;
    }

private:
    std::unordered_map<std::string, std::vector<int>> m;
};

类似题目

题目
leetcode:243. 单词列表中某两个单词的最短距离 Shortest Word Distance (两个单词不同,只调用一次) 想办法定位 word1 word2 在数组中的位置, 然后计算其相对距离: 用两个变量 p1,p2 初始化为 -1,然后遍历数组,遇到单词1,就将其位置存在 p1 里,若遇到单词2,就将其位置存在 p2 里,如果此时 p1, p2 都不为 -1 了,那么更新结果
leetcode:244. 单词列表中某两个单词的最短距离 Shortest Word Distance (两个单词不同,需要调用多次)想办法定位 word1 word2 在数组中的位置, 然后计算其相对距离:用一个map来建立每个单词与其所有出现的位置的映射。
leetcode:245. 单词列表中某两个单词的最短距离 Shortest Word Distance (两个单词可能相同,需要调用多次)想办法定位 word1 word2 在数组中的位置, 然后计算其相对距离: 三指针
leetcode:21. 合并两个有序链表 Merge Two Sorted Lists用两个指针分别执行两个链表,哪个小就移动哪个指针
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值