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;
        }
    };
  • 相关阅读:
    Python解释器的安装 安装IDE工具 pycharm
    推荐一些基础知识,希望对大家了解python语言及计算机有一些帮助!
    Typora 技巧
    js 与或运算符 || && 妙用
    数据类型和Json格式
    从事前端开发必须要了解的CSS原理
    CSS浏览器兼容
    用jQuery Mobile创建Web App
    让你的网站变成响应式的3个简单步骤
    CSS BFC hasLayout模型
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10141026.html
Copyright © 2011-2022 走看看