zoukankan      html  css  js  c++  java
  • LC 244. Shortest Word Distance II 【lock, Medium】

    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. Your method will be called repeatedly many times with different parameters. 

    Example:
    Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

    Input: word1 = “coding”, word2 = “practice”
    Output: 3
    
    Input: word1 = "makes", word2 = "coding"
    Output: 1

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

    利用一个字典记录所有相同的字母的位置,然后就是两个有序数组比较最近的元素。

    我设想把一个数组插入另一个数组,然后比较。C++ lower_bound大法。

    class WordDistance {
    private:
        unordered_map<string,vector<int>> map;
    public:
        WordDistance(vector<string> words) {
          for(int i=0; i<words.size(); i++) map[words[i]].push_back(i);
        }
        
        int shortest(string word1, string word2) {
          vector<int> l1 = map[word1];
          vector<int> l2 = map[word2];
          int idx = 0;
          int ret = INT_MAX;
          for(int i=0; i<l2.size(); i++){
            idx = lower_bound(l1.begin(), l1.end(),l2[i]) - l1.begin();
            if(idx == l1.size()){
              ret = min(ret, l2[i] - l1.back());
            }else if(idx == 0){
              ret = min(ret, abs(l2[i] - l1.front()));
            }else{
              ret = min(ret, abs(l2[i] - l1[idx]));
              ret = min(ret, abs(l2[i] - l1[idx-1]));
            }
            if(ret == 0) return 0;
          }
          return ret;
        }
    };

    下面是网上的简单做法,思路差不多,找最小的时候遍历,结果runtime24ms...

    class WordDistance {
    public:
        unordered_map<string, vector<int> > map;
        WordDistance(vector<string> words) {
            for(int i = 0; i < words.size(); i++){
                map[words[i]].push_back(i);
            }
        }
        int shortest(string word1, string word2) {
            vector<int> v1, v2;
            v1 = map[word1];
            v2 = map[word2];
            int diff = INT_MAX;
            for(int i = 0; i < v1.size(); i++)
                for(int j = 0; j < v2.size(); j++)
                    if(abs(v1[i]-v2[j]) < diff)
                        diff = abs(v1[i]-v2[j]);
            return diff;
        }
    };
  • 相关阅读:
    刷题19. Remove Nth Node From End of List
    刷题17. Letter Combinations of a Phone Number
    mysql图形化工具基本操作
    报错:ER_NO_DEFAULT_FOR_FIELD: Field 'status' doesn't have a default value
    express综合用法
    npm自定义上传
    node_第三方包下载文件package.jon详解
    正则表达式修改文字元素对齐方式
    初始化文章分类的方法 下拉的layui框
    标准git请求
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10141026.html
Copyright © 2011-2022 走看看