244. Shortest Word Distance II My Submissions Question

Problem

This is a follow up of Shortest Word Distance. 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.

Solution

用一个map<string, vector<int>>保存对应字符串所在的索引,然后枚举index[word1]index[word2]索引值,记录最小差值。

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

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

优化

  1. ordered_map,这里对于元素是否排序并不重要
  2. 由于是顺序扫描,所以索引应该是顺序插入同一个字符串的map中,所以相当于在两个排序的数组中找最小差值。有点类似于2sum的思想。根据当前索引值,让值小的那个的数组指针往后移一位。

code

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

    int shortest(string word1, string word2) {
        int minV = INT_MAX;
        int i = 0;
        int j = 0;
        int n = index[word1].size();
        int m = index[word2].size();
        while (i < n && j < m) {
            int index1 = index[word1][i];
            int index2 = index[word2][j];
            if (index1 < index2) {
                minV = min(index2 - index1, minV);
                i++;
            } else {
                minV = min(index1 - index2, minV);
                j++;
            }
        }
        return minV;
    }
};
    原文作者:楷书
    原文地址: https://www.jianshu.com/p/ee94b562c09c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞