前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >程序员面试金典 - 面试题 17.11. 单词距离(multimap平衡二叉搜索树)

程序员面试金典 - 面试题 17.11. 单词距离(multimap平衡二叉搜索树)

作者头像
Michael阿明
发布2020-07-13 16:03:04
5870
发布2020-07-13 16:03:04
举报

1. 题目

有个内含单词的超大文本文件,给定任意两个单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。

如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?

代码语言:javascript
复制
示例:
输入:words = ["I","am","a","student","from","a","university","in","a","city"],
word1 = "a", word2 = "student"
输出:1

提示:
words.length <= 100000

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-closest-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

类似题目:

LeetCode 243. 最短单词距离

LeetCode 244. 最短单词距离 II(哈希map+set二分查找)

LeetCode 245. 最短单词距离 III

  • 如果多次查询,建立multimap,查找 log⁡n\log nlogn 复杂度
  • 用multimap(底层是红黑树,平衡二叉搜索树)
  • key 是单词,value 是 序号
  • 该结构有序
代码语言:javascript
复制
class Solution {
	multimap<string,int> m;
public:
    int findClosest(vector<string>& words, string word1, string word2) {
        for(int i = 0; i < words.size(); ++i)
        	m.insert(make_pair(words[i],i));
        auto it1 = m.lower_bound(word1), end1 = m.upper_bound(word1);
        auto it2 = m.lower_bound(word2), end2 = m.upper_bound(word2);
        int dis = INT_MAX;
        while(it1 != end1 || it2 != end2)
        {
        	while(it1 != end1 && it2 != end2 && it1->second < it2->second)
        		dis = min(dis, it2->second - it1++->second);
        	while(it1 != end1 && it2 != end2 && it2->second < it1->second)
        		dis = min(dis, it1->second - it2++->second);
        	if(it1 == end1 && it2 != end2)
        	{
        		it1--;
        		while(it2 != end2)
        		{
        			dis = min(dis, abs(it1->second - it2++->second));
        		}
        		it1++;
        	}
        	else if(it1 != end1 && it2 == end2)
        	{
        		it2--;
        		while(it1 != end1)
        		{
        			dis = min(dis, abs(it2->second - it1++->second));
        		}
        		it2++;
        	}
        }
        return dis;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-02-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档