博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Shortest Word Distance II 最短单词距离之二
阅读量:7063 次
发布时间:2019-06-28

本文共 2030 字,大约阅读时间需要 6 分钟。

This is a follow up of . The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?

Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and 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.

Note:

You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

这道题是之前那道的拓展,不同的是这次我们需要多次调用求最短单词距离的函数,那么用之前那道题的解法二和三就非常不高效,而当时我们摒弃的解法一的思路却可以用到这里,我们用哈希表来建立每个单词和其所有出现的位置的映射,然后在找最短单词距离时,我们只需要取出该单词在哈希表中映射的位置数组进行两两比较即可,参见代码如下:

解法一:

class WordDistance {public:    WordDistance(vector
& words) { for (int i = 0; i < words.size(); ++i) { m[words[i]].push_back(i); } } int shortest(string word1, string word2) { int res = INT_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: unordered_map
> m;};

我们可以优化上述的代码,使查询的复杂度由上面的O(MN)变为O(M+N),其中M和N为两个单词的长度,我们需要两个指针i和j来指向位置数组中的某个位置,开始初始化都为0,然后比较位置数组中的数字,将较小的一个的指针向后移动一位,直至其中一个数组遍历完成即可,参见代码如下:

解法二:

class WordDistance {public:    WordDistance(vector
& words) { for (int i = 0; i < words.size(); ++i) { m[words[i]].push_back(i); } } int shortest(string word1, string word2) { int i = 0, j = 0, res = INT_MAX; 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: unordered_map
> m;};

本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。

你可能感兴趣的文章
独家!支付宝小程序技术架构全解析
查看>>
1100名达摩院“扫地僧”加持,阿里云的下一个十年
查看>>
python学习笔记-类对象的信息
查看>>
Java多线程(4):使用线程池执行定时任务
查看>>
前端之Sass/Scss实战笔记
查看>>
京东物流联手山西图灵打造智能供应链,让阅读更有趣 ...
查看>>
选择阿里云数据库HBase版十大理由
查看>>
多进程写入文件
查看>>
【运维趟坑回忆录 开篇】初入初创, 一脸懵
查看>>
你学不懂C语言,是因为不懂编写C程序的7个步骤 ...
查看>>
Prometheus VS InfluxDB
查看>>
《码出高效》学习笔记与书中错误记录
查看>>
东超科技获得千万级Pre-A轮融资,投资方为中科创星 ...
查看>>
翻译 | The Principles of OOD 面向对象设计原则
查看>>
个推基于Consul的配置管理
查看>>
zabbix安装
查看>>
阿里云RDS PostgreSQL GPU加速规格(支持GIS时空加速)发布
查看>>
Netflix Media Database - 架构设计和实现
查看>>
云HBase Spark分析引擎对接云数据库POLARDB
查看>>
揭秘 DockerCon 重量级演讲嘉宾(六)
查看>>