Golden programmer interview - face questions from 17.11 word (multimap balanced binary search tree)

1. Topic

There is a large text file that contains words, given any two words in this file to find out the shortest distance of the two words (separated by the number of words). If you find the process is repeated several times in this document, each looking for different words, this you can optimize it?

示例:
输入:words = ["I","am","a","student","from","a","university","in","a","city"],
word1 = "a", word2 = "student"
输出:1

提示:
words.length <= 100000

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/find-closest-lcci
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. Problem Solving

  • If multiple queries, build multimap, find log n \log n Complexity
  • With the multimap (bottom layer is red-black tree, balanced binary search tree)
  • keyIs the word, valueis the serial number
  • The structural order
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;
    }
};

Here Insert Picture Description

Published 641 original articles · won praise 494 · Views 140,000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/104315448