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

1. 题目

有个内含单词的超大文本文件,给定任意两个单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?

示例:
输入: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. 解题

  • 如果多次查询,建立multimap,查找 log n \log n 复杂度
  • 用multimap(底层是红黑树,平衡二叉搜索树)
  • key 是单词,value 是 序号
  • 该结构有序
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;
    }
};

在这里插入图片描述

发布了641 篇原创文章 · 获赞 494 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/104315448